# Memory layout of C programs and stack frames


C program layout

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Code segment]
[Data segment]
[BSS  segment]
[Heap        ]
[Stack       ]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Code/Text segment

- Contains executable instructions.
- Read-only memory.
- Shared (only a single copy needs to be in memory).


Data segment

- Contains initialized global or static variables.
- Read-write memory.


BSS segment

- Contains uninitialized global or static variables.
- Read-write memory.


Heap

- Read-write memory.
- Grows to higher memory addresses.
- Managed by malloc, realloc and free functions.


Stack

- LIFO structure.
- Read-write memory.
- Grows to lower memory addresses.
- Contains stack frames (one for each pushed function):

Low memory addresses
~~~~~~~~~~~~~~~~~~~~~
[Local variables   ]
[Old Base Pointer  ]
[Return address    ]
[Function arguments]
~~~~~~~~~~~~~~~~~~~~~
High memory addresses

Data and BSS example

# cat c-layout.c
#include <stdio.h>

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252       8    1316     524 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      12    1320     528 c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     252      16    1324     52c c-layout
# cat c-layout.c
#include <stdio.h>

int global;

int main(){
        static int i=10;
        return 0;
}
# gcc -o c-layout c-layout.c
# size c-layout
   text    data     bss     dec     hex filename
   1056     256      12    1324     52c c-layout

No comments: