Memory Segmentation

The memory layout of a program shows how its data is stored in memory during execution. When a C program is executed, its memory is divided into several segments, each serving a distinct purpose: Memory is divided into sections such as code, data, heap, and stack.

the data segment can be sub-divided into:

static data can be grouped into:

dynamic data can be divided in 2:

Memory layout:
Attachments/Memory-Layout-of-C-Program.webp

Text segment

Also called code segment, contains the instructions to execute a program

Data Segment (Dynamic / Static)

A. Initialized Data Segment

As the name suggests, it is the part of the data segment that contains global and static variables that have been initialized by the programmer.

B. Uninitialized Data Segment

.bss Segment: Contains global and static variables that are uninitialized or initialized to zero.

Example:

#include <stdio.h>
#include <stdlib.h>

int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int b[20]; /* Uninitialized, so in the .bss segment */

int main()
{
    ;
}

! 400

Example 2: Initialised values

#include <stdio.h>

// Global variables (stored in initialized data segment)
int globalVar = 10;
char message[] = "Hello";

int main()
{
    // Static variable (also stored in initialized data segment)
    static int staticVar = 20;
    printf("Global variable: %d\n", globalVar);
    printf("Static variable: %d\n", staticVar);
    printf("Message: %s\n", message);
    
    return 0;
}

Output

Global variable: 10
Static variable: 20
Message: Hello

The above variables a and b will be stored in the Initialized Data Segment.

Example 3: uninitialised values

#include <stdio.h>

// Global uninitialized variables (stored in BSS segment)
int globalVar;
char message[50];

int main()
{
    // Static uninitialized variable (also stored in BSS)
    static int staticVar;
    
    // Assigning values at runtime
    globalVar = 10;
    staticVar = 20;
    snprintf(message, sizeof(message), "Hello BSS");
    
    printf("Global variable: %d\n", globalVar);
    printf("Static variable: %d\n", staticVar);
    printf("Message: %s\n", message);
    
    return 0;
}

Heap Segment

Stack Segment

#include <stdio.h>

void func() {
    
    // Stored in the stack
    int local_var = 10;  
}

int main() {
    func();
    return 0;
}

When the stack and heap meet, the program’s free memory is exhausted

Powered by Forestry.md