Memory layout of C program consists of 5 segments
1. Text Segment
2. Initialized Data Segment
3. Uninitialized Data Segment
4. Heap
5. Stack
Let us see one by one.
1. Text
The text segment is also known as a code segment which contains the binary of the program(Object Files). It is the lowermost layer of memory layout and a sharable so that only a single copy needs to be in memory for frequently executed programs. The text segment is a read-only segment that prevents a program from being accidentally modified.
2. Initialized Data Segment
The initialized data segment also called a Data Segment. It contains initialized global and static variables that are initialized by the programmer. It has read and write permission so that the value of the variable can be changed at a run time.
This segment can be further classified into an initialized read-only area and an initialized read-write area.
3. Uninitialized Data Segment
Data in this segment are initialized by the kernel to zero before program starts executing.
4. Heap
The heap area begins at the end of the BSS segment and grows to larger addresses from BSS Segment. This area is managed by malloc, realloc, and free.
The Heap area is shared by all shared libraries and dynamically loaded modules in a process. When memory needs to be allocated using malloc and calloc function, heap grows upward as shown in the above diagram.
5. Stack
The stack contains a LIFO structure. Function variables are pushed onto the stack when called and functions variables are popped off the stack when return. Stack pointer (SP) register tracks the top of the stack. When the stack pointer meets the heap pointer, free memory will be exhausted. This segment size is variable as per function calls, local variables, and function parameters.