Skip to main content...
How Computers Work + OS Essentials
25 min

Day 3: Virtual memory; stack vs heap

Virtual memory: everyone gets their own universe

Every process sees its own private address space, from address 0 up to some large number, as if it owned all the RAM in the machine. This is a lie the kernel maintains on purpose: virtual memory. The kernel (with hardware help — the MMU) maps each process's virtual addresses to real physical RAM addresses behind the scenes, and can even back some of that virtual memory with disk (swap) when RAM is full.

Why the lie is useful

Because every process's address space is independent, one process can't accidentally (or maliciously) read or corrupt another's memory just by guessing an address — the mapping simply doesn't exist for them. It also means a program can be written as if it has a huge, contiguous chunk of memory, even if physical RAM is fragmented.

Stack vs heap

Within a process's memory, the stack holds function call frames — local variables, return addresses — and grows/shrinks automatically as functions are called and return. It's fast, but limited in size (a runaway recursive function causes a stack overflow). The heap is for memory you explicitly allocate that needs to outlive a single function call — objects, arrays, anything with a lifetime you control. It's flexible but slower to manage, and if you forget to free it (in languages without garbage collection), you get a memory leak.

  • Stack: automatic, fast, size-limited, LIFO (last in, first out)
  • Heap: manual or garbage-collected, flexible size, has real management overhead
  • JavaScript objects/arrays live on the heap; primitive locals often live on the stack

Payoff, later

Phase 28's memory-debugging drill is entirely about heap objects that should have been garbage-collected but are still reachable somewhere — a leak is, precisely, heap memory nobody frees because it's still (accidentally) referenced.

Key terms

Virtual memory
Each process's private view of memory, mapped by the kernel/MMU to real physical RAM (or disk-backed swap).
Stack
Automatically managed memory for function call frames and local variables.
Heap
Manually or GC-managed memory for data with a lifetime beyond a single function call.
Stack overflow
A crash caused by the call stack growing beyond its allotted size, usually from unbounded recursion.

A deeply recursive function with no base case eventually crashes with what?

We use cookies

We use cookies to enhance your browsing experience, serve personalized content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Learn more

    Day 3: Virtual memory; stack vs heap | RBTechIconX