π§ 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
| Segment | Description | Grows | Example |
|---|---|---|---|
| π§ Text (Code) | Binary instructions of the program | β Fixed | main(), if, loops |
| π¦ Data | Global/static variables that are initialized | β Fixed | int x = 5; |
| π² BSS | Global/static variables that are uninitialized | β Fixed | static int x; |
| π Heap | Memory for dynamic allocation (malloc, new) | πΌ Upward | int* ptr = malloc(100); |
| π Stack | Stores function calls, parameters, local vars | π½ Downward | int 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.