Open In App

Memory Layout of C++ Program

Last Updated : 30 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The memory layout of a C++ program shows how various parts (like code, stack, heap, and data) are organized in memory during execution. Understanding it helps manage memory efficiently and avoid issues like leaks and stack overflows.

Memory-Layout-of-C-Program

A C++ program's memory is typically divided into distinct regions, each with its own purpose during runtime.

1. Text Segment (Code Segment)

The text segment stores the program’s compiled machine code (functions and methods) and is usually read-only to enhance safety. Its size varies based on code complexity.

2. Data Segment

The data segment stores global and static variables defined by the programmer. This segment is located just above the text segment and is divided into two parts:

A. Initialized Data Segment

Stores global and static variables that are assigned a value at declaration.

C++
// Global variable
int a = 50;

// Static variable
static int b = 100;

Both a and b are stored in the initialized data segment.

B. Uninitialized Data Segment (BSS)

Holds global and static variables that have not been explicitly initialized. The system automatically sets these to zero at runtime.

C++
// Global variable
int c;

// Static variable
static int d;

c and d are placed in the BSS segment.

3. Heap Segment

The heap is the memory region used for dynamic allocation at runtime. Memory in the heap is managed manually using operators like new/delete or functions like malloc()/free().

C++
#include <iostream>
using namespace std;

int main() {
    
    // Dynamically allocate array on heap
    int* arr = new int[10];
    delete[] arr;
    return 0;
}

The memory pointed to by arr resides in the heap.

4. Stack Segment

The stack is used for:

  • Local variables
  • Function parameters
  • Return addresses

Each function call creates a stack frame, which is pushed to the stack. When the function finishes, its frame is popped off.

Example:

C++
#include <iostream>
using namespace std;

void foo() {
    
    // Stored in stack
    int local = 42;
    cout << local << endl;
}

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

Output
42

The stack grows downward (toward lower memory addresses), opposite to the heap.

Practical Examples

C++
#include <iostream>
#include <cstdlib>
using namespace std;

int g = 77;

void show() {
    int local = 5;
    cout << "Local address: " << &local << endl;
}

int main() {
    int* heapVar = new int;
    cout << "Function address: " << (void*)&show << endl;
    cout << "Global address: " << &g << endl;
    cout << "Heap address: " << heapVar << endl;
    show();
    delete heapVar;
    return 0;
}

Output
Function address: 0x400c00
Global address: 0x6012c0
Heap address: 0x94d4c20
Local address: 0x7fff9e84be8c



Article Tags :
Practice Tags :

Similar Reads