Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about memory/malloc

How are variables really stored in memory? I ask this because say you malloc a segment of memory and assign it to a pointer e.g.

int *p = malloc(10 * sizeof(int));

and then run a for loop to assign integers through p - this seems different to declaring an int variable and assigning an integer to it like:

int x = 10;

Because it's a more explicit declaration that you want an int stored in memory, whereas in malloc it's just a chunk of memory you're traversing through pointer arithmetic.

Am I missing something here? Much thanks.

like image 564
trueskyblue Avatar asked Nov 26 '25 00:11

trueskyblue


1 Answers

when you need an array of data, for example when you receive numbers from the user but don't know the length you can't use a fixed number of integers, you need a dynamic way to crate memory for those integers. malloc and his friends let you do that. among other things:

  • malloc let you create memory dynamically in the size you need right now.
  • while using malloc the memory will not be freed when exiting the scope.
  • using malloc for let's say array of 10 item or create an array of 10 items on the stack there is no difference in the sense of " explicit declaration that you want an int stored in memory", there is just differences in what i've written here and some more

here is an article on the differences between heap and stack

i'm writing the pros of each way:

Stack

  • very fast access
  • don't have to explicitly de-allocate variables
  • space is managed efficiently by CPU, memory will not become fragmented
  • local variables only
  • limit on stack size (OS-dependent)
  • variables cannot be resized

Heap

  • variables can be accessed globally
  • no limit on memory size
  • (relatively) slower access
  • no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
  • you must manage memory (you're in charge of allocating and freeing variables)
  • variables can be resized using realloc()
like image 75
No Idea For Name Avatar answered Nov 28 '25 16:11

No Idea For Name