Operating Systems•25 min read•Advanced
Memory Management & Virtual Memory
Stack vs heap, paging, the page table, and what 'segmentation fault' really means.
Stack and heap
- STACK — fixed-size region per thread; holds function call frames (locals, return addresses); allocated/freed by the function call/return; very fast.
- HEAP — dynamically allocated memory; objects you create with `new`/`malloc`/`{}`/etc.; freed manually (C/C++) or by GC (Python, JS, Java).
- Stack overflow — too-deep recursion fills the stack. Heap exhaustion — too much allocation = OutOfMemoryError.
Virtual memory
Every process sees what looks like a big, flat, private address space — typically 2⁶⁴ bytes on 64-bit systems. This is a LIE. The OS maintains a per-process PAGE TABLE that maps virtual addresses (what the program sees) to physical addresses (actual RAM). The illusion buys three things:
Virtual memory: how a virtual address becomes a physical address
The CPU consults the page table on every memory access. Invalid entries trigger a page fault.
Virtual address
0x0142 = vPage 1 | offset 0x42
↓ Look up vPage in the page table
→ Physical addr 0x0042= pPage 0 | offset 0x42
Page table
v0→p2valid
v1→p0valid
v2→p3valid
v3→unmappedinvalid
v4→p1valid
v5→unmappedinvalid
v6→unmappedinvalid
v7→unmappedinvalid
Program reads vAddr 0x0142. Top bits = vPage 1, low bits = offset 0x42.
- Isolation — process A's address 0x1000 and process B's address 0x1000 map to different physical pages.
- Larger-than-RAM workloads — pages can be swapped to disk and brought back on demand.
- Security — pages can be marked read-only or non-executable (preventing buffer-overflow exploits).
What 'segfault' actually means
A segmentation fault happens when your program tries to access a virtual address that isn't mapped — or is mapped but with the wrong permissions (writing to a read-only page, executing data, etc.). The CPU traps to the kernel; the kernel kills your process and dumps core.
💡 Tip
The first 4KB of every process's address space is intentionally unmapped. That's why dereferencing a NULL pointer (address 0) reliably crashes, instead of corrupting random memory.