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
|-------------------------|
| Text Segment | <- Program code
|-------------------------|
| Initialized Data (DS) | <- Global/static vars with values
|-------------------------|
| Uninitialized Data (BSS)| <- Global/static vars without values
|-------------------------|
| Heap | <- Dynamic memory (grows upward)
|-------------------------|
| Stack | <- Local variables, function calls (grows downward)
|-------------------------|
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
#include <stdio.h>
#include <stdlib.h>
int global_var = 10; // Data Segment (initialized)
static int static_var; // BSS Segment (uninitialized)
int main() {
int local_var = 20; // Stack
int *ptr = (int *)malloc(sizeof(int)); // Heap
*ptr = 30;
printf("Global: %d\n", global_var);
printf("Static: %d\n", static_var);
printf("Local: %d\n", local_var);
printf("Heap: %d\n", *ptr);
free(ptr);
return 0;
}
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