Skip to main content

25. Memory Layout in C

 

Memory Layout in C

When we create a C program and run the program, its executable file is stored in the RAM of the computer in an organized manner.

The memory layout for C program can be shown below:


The C program consists of the following sections in the program:

  • Code segment or Text segment
  • Variables or Data section
  • Stack
  • Heap

Text segment

The text segment is also known as the code segment. When we compile any program, it creates an executable file like .exe, etc., that gets stored in the text or code section of the RAM memory. If we store the code or text in the hard disk, then the speed for accessing the instructions from the hard disk becomes slower, whereas the RAM is directly connected to the data and address bus, so accessing data from the RAM is faster.

Variables or Data Section

The data which we use in our program will be stored in the data section. By variables, we mean both global and static variables. Global variables can be used anywhere in the program, while static has its limitations inside the function. The variable segment is further divided into two segments, depending on the data they can store.

  • Initialized Data Segment: Stores initialized data i.e. data whose value is already given. This segment is also known as the data segment. This data segment can be further classified into categories:
    • Initialized read-only area: It is an area where the values of variables cannot be modified.
    • Initialized read-write area: It is an area where the values of variables can also be altered.
  • Uninitialized Data Segment: Stores uninitialized data i.e. data whose variable is declared only. This segment is also known as the .bss segment. The .bss segment stands for Block Started by Symbol.

Stack

The variables which are declared inside the function are stored in the stack. The stack section plays a very important role in the memory because whenever the function is called, a new stack frame is created.

Initially stack looks like a bucket in which the last entry to be inserted will be the first one to get out. That is why it is known as LIFO data structure i.e., last in first out.

Stack Overflow

When a stack gets exhausted due to bad programming skills or some logical error, the phenomenon is known as stack overflow. When the function is called itself again and again inside the same function which causes the stack overflow condition and it leads to the segmentation fault error in the program.

Heap

Heap memory is used for the dynamic memory allocation. It's size increases when we allocate memory dynamically. To use the heap data structure, we have to create a pointer in our main function that will point to some memory block in a heap. The disadvantage of using heap is that the memory will not get freed automatically when the pointer gets overwritten.

Comments