1. C Memory Layout ( Source )
Memory representation of C program consists of :
1.
Text segment -
- It contains executable instructions.
- A text segment may be placed below the heap or
stack (to prevent heaps and stack overflows from overwriting it.)
- Usually, the text segment is sharable (so that only a single copy
is needed) and read-only( to prevent accidental modification.)
2.
Initialized data segment -
- It is a portion of virtual address space of a program.
- It
contains the global variables and static variables initialized by programmer.
- Data segment is not read-only(variables can be altered at run time.)
- It can be further classified into initialized read-only area and initialized read-write area.
For instance,
char s[] = “hello world” would be stored in
initialized read-write area.
const char* string = “hello world” makes the string literal “hello
world” to be stored in
initialized read-only area and the character
pointer variable string in initialized read-write area.
3. Uninitialized data segment( “bss” segment)
- Data in this segment is initialized by the kernel to arithmetic
0.
- It contains
all global variables and static variables that are initialized to zero
or do not have explicit initialization.
4. Stack
- The stack area and heap area grow in the
opposite direction; when the stack pointer met the heap pointer, free
memory was exhausted.
- The stack area contains the program stack. A “stack pointer”
register tracks the top of the stack; it is adjusted each time a value
is “pushed” onto the stack.
- The set of values pushed for one function
call is termed a “stack frame”; A stack frame consists at minimum of a
return address.
- Each time a function is
called, the address of where to return to and certain information about
the caller’s environment, such as some of the machine registers, are
saved on the stack.
- The newly called function then allocates room on the
stack for its automatic and temporary variables.
- This is how recursive
functions in C can work. Each time a recursive function calls itself, a
new stack frame is used, so one set of variables doesn’t interfere with
the variables from another instance of the function.
5. Heap
- Heap is the segment where dynamic memory allocation usually takes place.
- The Heap area is managed by malloc, realloc,
and free, which may use the brk and sbrk system calls to adjust its
size
- The Heap
area is shared by all shared libraries and dynamically loaded modules in
a process.