sometimes people asks question about runtime memory layout of c programs. before going into details let us write a simple code:

#include<sdtio.h>
#include<stdlib.h>
 
int a;  /* global uninitialized data  stored in bss*/
int c=10;        /* global initialized data stored in data segment */      
 
static aa;       /* global uninitialized static data stored in bss,initialized zero at load time*/
static bb=10;       /* global initialized static data , stored in data segment */
 
int main()
{
   int b; /* local uninitialized data stored in stack*/
   int d=20; /* local initialized data stored in stack */
 
     static aaa;       /* local uninitialized static data stored in bss segment*/
     static bbb=10;       /* local initialized static data, stored in data segment */
     int* aps;
     aps = (int*)malloc(sizeof(int)); /* dynamic memory stored in heap */
     free(aps); 
return 0;
}

Memory Layout of C program

memory representation of C program
Memory Layout of C program: Tutorial with example code

 

 

 

  1. Code segment
  2. Data segment ( initialized data)
  3. BSS (uninitialized data)
  4. Heap segment
  5. Stack segment
  6. start segment

Start segment

Every executable has an start segment which holds information that is used by the operating system to load the program. this stores the size information of other segments.

Code segment

This segment holds the executable code i.e. machine instructions that your CPU going to execute

Data segment

This segment holds global initialized data. The code and data segments are copied directly into memory by operating system.

 

BSS ( block start by symbol)

BSS segments holds all(global and static) uninitialized data.

 

Stack segment

all automatic variable are stored in stack area. as well as return value of a function and its arguments,program environmental variables are also being stored in this area.

 

Heap segment

Dynamic memory allocation take place in heap segment.

by objdump command we can see the storage location of data member of above program:

by objdump command we can see the storage location of data member of above program:

mic@mic-Vostro-1550:~$gcc test.c -o test
mic@mic-Vostro-1550:~$ objdump -d -j .data test
test:     file format elf64-x86-64
Disassembly of section .data:

0000000000601038 :
...
0000000000601040 :
...
0000000000601048 :
  601048:    0a 00 00 00                                         ....
000000000060104c :
  60104c:    0a 00 00 00                                         ....
0000000000601050 :
601050:    0a 00 00 00

mic@mic-Vostro-1550:~$ objdump -d -j .bss test

test:     file format elf64-x86-64


Disassembly of section .bss:

0000000000601054 :
  601054:    00 00                    add    %al,(%rax)
    ...

0000000000601058 :
  601058:    00 00 00 00                                         ....

000000000060105c :
  60105c:    00 00 00 00                                         ....

0000000000601060 :
    ...

 



Related Contents to follow