Memory Layout of C Programs

The memory layout for C programs is like below. There are few levels. These are −

  • Stack Segment
  • Heap Segment
  • Text Segment
  • Data segment

Now let us see what are the functionalities of these sections.

Sr.NoSections & Description
The process Stack contains the temporary data such as method/function parameters, return address and local variables. It is an area of memory allotted for automatic variables and function parameters. It also stores a return address while executing function calls. Stack uses LIFO (Last- In-First-Out) mechanism for storing local or automatic variables, function parameters and storing next address or return address. The return address refers to the address to return after completion of function execution. This segment size is variable as per local variables, function parameters, and function calls. This segment grows from a higher address to a lower address.
This is dynamically allocated memory to a process during its run time. This is area of memory allotted for dynamic memory storage such as for malloc() and calloc() calls. This segment size is also variable as per user allocation. This segment grows from a lower address to a higher address.
Let us now check how the segments (data and bss segments) size vary with a few sample programs. Segment size is known by executing the command “size”.
This includes the current activity represented by the value of Program Counter and the contents of the processor's registers. It is represented by .text section. This defines an area in memory that stores the instruction codes. This is also a fixed area.
This section contains the global and static variables. It is represented by .data section and the .bss. The .data section is used to declare the memory region, where data elements are stored for the program. This section cannot be expanded after the data elements are declared, and it remains static throughout the program.
The .bss section is also a static memory section that contains buffers for data to be declared later in the program. This buffer memory is zero-filled.

The data segments can be divided into more two parts.

Sr.NoSections & Description
1Initialized data segment
This is a portion of the object file or program’s virtual address space that consists of uninitialized static and global variables. Un-initialized data segment is also called BSS (Block Started by Symbol) segment.
2Un-initialized data segment
This is read-write, since the values of variables could be changed during run time. This segment also has a fixed size.