🧠 High-Level Layout of a Process in Memory

When a process is loaded into memory (RAM), it’s organized into five main segments:

  ↑ High Memory
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚       Stack               β”‚ ← Grows Down
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚       Heap                β”‚ ← Grows Up
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚   Uninitialized Data (BSS)β”‚
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚   Initialized Data (Data) β”‚
  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚       Code (Text)         β”‚ ← Fixed, Read-Only
  ↓ Low Memory

πŸ” Breakdown of Each Segment

SegmentDescriptionGrowsExample
🧠 Text (Code)Binary instructions of the program❌ Fixedmain(), if, loops
πŸ“¦ DataGlobal/static variables that are initialized❌ Fixedint x = 5;
πŸ”² BSSGlobal/static variables that are uninitialized❌ Fixedstatic int x;
πŸ“ˆ HeapMemory for dynamic allocation (malloc, new)πŸ”Ό Upwardint* ptr = malloc(100);
πŸ“‰ StackStores function calls, parameters, local varsπŸ”½ Downwardint x = 10; in a function

βš™οΈ Real Example in C

#include <stdlib.h>
 
int global_init = 10;   // β†’ Data segment
int global_uninit;      // β†’ BSS segment
 
int main() {
    int local_var = 5;           // β†’ Stack
    int* heap_var = malloc(100); // β†’ Heap
    return 0;                    // Code in Text segment
}

πŸ“¦ Additional Info

  • Stack and Heap grow toward each other, but are protected by virtual memory boundaries.

  • Segmentation fault or stack overflow happens when:

    • Stack grows too large

    • Heap corrupts stack or vice versa


πŸ” Memory Protection by OS

  • Code segment is read-only β€” protects against self-modifying code.

  • Heap and stack have guard pages to catch overflows.

  • Each process has its own virtual address space (via paging) β†’ isolation from other processes.


🧠 Interview-Ready Summary:

A process in memory is divided into segments: the text (code) segment, data and BSS segments for global/static variables, a heap for dynamic memory allocation, and a stack for function calls and local variables.
The stack grows downward and the heap grows upward, and both are isolated in virtual memory for safety and control.