Memory Layout of C Programs - Ocean of Programming

Friday 14 August 2020

Memory Layout of C Programs

 

        In this article, I am going to explain the Memory Layout of C program before that if you have not read my previous article Compilation Stages in C programing you read that click here

 

     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

      

     Uninitialized Data segment is also called as BSS. This segment starts at the end of the data segment. It contains all global variables and static variables that are initialized to zero or do not have explicit initialization and pointer are pointers with the null pointer. 

    Data in this segment are initialized by the kernel to zero before program starts executing. 
  
 

4. Heap

    Heap is the segment is used to allocate memory at the run time.
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 area adjoined the heap area and grew the opposite direction. The stack contains temporary data such as a local address, function parameters and return address.
    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.


 
 

No comments:

Post a Comment