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:

  1. Text (Code) Segment – Stores the compiled program instructions
  2. Data Segment – Stores global and static variables
  3. Initialized data segment
  4. Uninitialized (BSS) segment
  5. Heap Segment – Stores dynamically allocated memory (malloc, calloc, realloc)
  6. 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

  1. Stores executable instructions
  2. Usually read-only to prevent accidental modification
  3. Shared between processes to save memory

b) Data Segment

  1. Initialized Data: global/static variables with assigned values
  2. BSS Segment: global/static variables without initial value (default 0)

c) Heap Segment

  1. Used for dynamic memory allocation using malloc(), calloc(), realloc()
  2. Grows upward
  3. Managed manually using free()

d) Stack Segment

  1. Stores local variables, function parameters, and return addresses
  2. Grows downward
  3. 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:

  1. global_var → Data segment
  2. static_var → BSS segment
  3. local_var → Stack
  4. ptr → Heap (dynamic memory)

5. Key Points to Remember

  1. Stack: function calls, local variables, automatic management
  2. Heap: dynamic memory, manually managed with malloc/free
  3. Data Segment: global/static variables
  4. Text Segment: executable code
  5. Understanding memory layout helps prevent stack overflow, memory leaks, and segmentation faults