C Segments
Generally C programs are divided into several segments.
- text — the compiled code
- data & bss — static data areas
- heap — data allocated with
malloc
- stack — local variables
Example
Start with the following program. Note that all the variables are pointers, because arrays are implemented as constant pointers.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define PRINTIT(X) \ do { \ printf("Location of %-7s is %0*lX\n", \ #X, 16, (unsigned long)(void *)X) ;\ } while(0) uint32_t Aglobal[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const uint32_t Aconst[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; uint32_t Abss[10] ; void subr(void) { uint32_t ASlocal[10] ; PRINTIT(ASlocal) ; } int main(int argc, char** argv) { uint32_t AMlocal[10] ; uint32_t *Amalloc ; Amalloc = (uint32_t *)malloc(10*sizeof(uint32_t)) ; PRINTIT(Aglobal) ; PRINTIT(Aconst) ; PRINTIT(Abss) ; PRINTIT(Amalloc) ; PRINTIT(AMlocal) ; subr() ; PRINTIT(main) ; PRINTIT(subr) ; PRINTIT(printf) ; return (EXIT_SUCCESS); }
Here is an abbreviated and sorted version of the result of running nm on the compiled and linked program. Notice that malloc
are printf
are undefined because they are stored in a dynamic library.
0000000000400420 T _init 0000000000400490 T _start 000000000040057d T subr 00000000004005a7 T main 0000000000400780 R Aconst 0000000000601000 d _GLOBAL_OFFSET_TABLE_ 0000000000601040 D __data_start 0000000000601060 D Aglobal 0000000000601088 B __bss_start 00000000006010c0 B Abss U malloc@@GLIBC_2.2.5 U printf@@GLIBC_2.2.5
When the program is run, it produces the following output which displays the addresses of
Amalloc
in the heap and
AMlocal
and ASlocal
in the stack.
The addresses of the functions don’t make much sense.
(Some are even odd.)
The C defintion states that casting a function to (void *)
is undefined.
Location of Aglobal is 0000000000601060 Location of Aconst is 0000000000400780 Location of Abss is 00000000006010C0 Location of Amalloc is 00000000022B1010 Location of AMlocal is 00007FFF893D8C40 Location of ASlocal is 00007FFF893D8BE0 Location of main is 00000000004005A7 Location of subr is 000000000040057D Location of printf is 0000000000400450