Memory layout / Address space of variables in C program

Following is the program which details the simple memory layout of the c program. As we can see in this, program memory is divided into  the text, various data, and stack and heap sections.

 $ vim address_space.c  
#include <stdio.h>
int bss_var; /* Uninitialized global variable */
int data_var = 1; /* Initialized global variable */
int main(int argc, char **argv) {
        void *stack_var;
        /* Local variable on the stack */
        stack_var = (void *)main;
        /* Don't let the compiler */
        /* optimize it out */
        printf("Hello, World! Main is executing at %p\n", &stack_var);
        printf("This address (%p) is in our stack frame\n", &stack_var);
        /* bss section contains uninitialized data */
        printf("This address (%p) is in our bss section\n", &bss_var);
        /* data section contains initializated data */
        printf("This address (%p) is in our data section\n", &data_var);
        return 0;
}
 $ gcc -o address_space address_space.c 
 $ ./address_space
Hello, World! Main is executing at 0x804846b
This address (0xbffccbb8) is in our stack frame
This address (0x804a028) is in our bss section
This address (0x804a020) is in our data section

Refer https://en.wikipedia.org/wiki/Data_segment for more details.

Leave a Comment