Skip to content
Advertisement

Memory layout of C program

When I run this C code, I get the following output as shown. What these numbers mean, why they are like that and what can we learn from it about the position of the variables.

#include <stdio.h>
#include <stdlib.h>

int f(int i,int j, int *ptr);

int main (int argc, char *argv[]) {
 int a=2;
 int b=4;
 int *age = malloc(sizeof(int));
 *age =0;
 *age +=a;
 printf("Main Address of local variable a=%u,b=%u and *age=%u and address of dynamic variable %un", (unsigned int)&a,(unsigned int)&b,(unsigned int) &age, (unsigned int) age);

f(a,b, age);
 return 0;
}

int f(int i,int j, int *ptr) {
 printf("Function f: address of local variable a=%u,b=%u and address of dynamic variable %un (unsigned int) &i,(unsigned int)&j,(unsigned int) ptr);
}

Output:

ubuntu@ubuntu-VirtualBox:~/code$ ./var0
Main Address of local variable a=3212861652,b=3212861656 and
*age=3212861660 and address of dynamic variable 158076936
Function f: address of local variable
a=3212861616,b=3212861620 and address of dynamic variable
158076936

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement