Memory layout of a program refers to the organisation of memory to various components of a program. When we run our program, Operating System assigns a block of memory for our process. That memory block contains different segments. In this article, we will discuss about the different memory segments.
When a C/C++ program is executed, the memory block of the running process contains following segments:
The text segment, also known as the code segment, it stores the executable code/instructions of a program. When we compile our code, it generates machine instructions of the program’s functions and methods. These instructions are stored in the text segmenet of memory. It is a read-only area, so that no one can modify the instructions at runtime.
The data segment is internally divided into two parts:
This stores global and static data that have been initialized with a value other than zero. This data is not read-only, it means data in this part of segment can be modified at runtime.
This is also known as BSS segment.
This stores the global and static variables that are not initialized. This memory segement is initialized with 0 by the kernal, berfore the start of execution of program. Therefore, all the global variables and static variables, which are not initialized in the program, gets automatically initialized with 0 when execution of program starts.
The heap segment is used for dynamic memory allocation during runtime. For memory allocation and deallocation C/C++ provides various functions, like new
, delete
, malloc()
, calloc()
, and free
. Program can allocate and deallocate memory at runtime, and an inefficient memory management of the heap can lead to the problems of fragmentation or memory leaks.
The stack segment contains function call information. This includes,
The stack segment is helpful in controlling the execution flow of the program. Whenever we call a function, a new stack frame gets created and all the local variables in that function get stored in that stack in last-in and first-out order (LIFO Principle). When a function ends, its stack frame gets popped out from the stack, all the variables on this stack get removed from the stack in last and first out order i.e. the variable which was declared at last in function will be popped out from stack first and similarly variable declared at the start of function will be popped out from the stack in last when stack enwinding is happenening.
This segment stores command-line arguments passed to the program during execution.
The environment segment contains the environment variables. This a for the operating system to pass information and configuration data to a the program.
It is essential for a C/C++ programmer to understand the memory layout of a program. It will help in optimisation, and debugging. Awareness of this memory model is especially beneficial when working with embedded systems, operating systems, and applications that require precise control over system resources.