Memory Layout of a C Program (Complete Guide with Diagram & Examples)
This tutorial explains the memory layout of a C program, showing how memory is organized into different segments like code, data, heap, and stack. Understanding memory layout helps in efficient programming, debugging, and avoiding memory issues.
1. Overview
When a C program runs, the memory is divided into several segments:
- Text (Code) Segment – Stores the compiled program instructions
- Data Segment – Stores global and static variables
- Initialized data segment
- Uninitialized (BSS) segment
- Heap Segment – Stores dynamically allocated memory (malloc, calloc, realloc)
- Stack Segment – Stores local variables and function call information
2. Memory Layout Diagram
3. Details of Each Segment
a) Text Segment
- Stores executable instructions
- Usually read-only to prevent accidental modification
- Shared between processes to save memory
b) Data Segment
- Initialized Data: global/static variables with assigned values
- BSS Segment: global/static variables without initial value (default 0)
c) Heap Segment
- Used for dynamic memory allocation using
malloc(),calloc(),realloc() - Grows upward
- Managed manually using
free()
d) Stack Segment
- Stores local variables, function parameters, and return addresses
- Grows downward
- Automatic memory management (created/destroyed when function is called/returns)
4. Example: Memory Usage in C
Explanation:
global_var→ Data segmentstatic_var→ BSS segmentlocal_var→ Stackptr→ Heap (dynamic memory)
5. Key Points to Remember
- Stack: function calls, local variables, automatic management
- Heap: dynamic memory, manually managed with
malloc/free - Data Segment: global/static variables
- Text Segment: executable code
- Understanding memory layout helps prevent stack overflow, memory leaks, and segmentation faults