Memory layout of C program

In general, memory is laid out as such:

High Addresses
|    Stack    |
|             |
|    Heap     |
| Static Data |
|    Code     |
 Low Adresses

When you initialize a local variable like a, b, age, each variable is allowed to occupy a space on the the stack which is determined by its type. In other words, it gets its own an address on the stack. Notice that because of the way memory is laid out, these variables have higher address values, consistent with the diagram above. Now, understand that the address of a is 3212861652 and its value is 2; the address of age is 3212861660, and its value is 158076936.

That value of age is an address of memory on the heap. That is what is returned by a call to malloc. When you malloc(sizeof(int)), you’re asking for an address on the heap that can be used to store sizeof(int) bytes freely. The heap is much lower down, so the value of age is much lower than the address it is stored at.

Leave a Comment