ELI5 · How computers work

Stack vs heap.

A neat stack of trays you add and remove from the top, versus a big warehouse where you ask for space and must give it back.

A program has two main places to keep data in memory, and they work very differently. The stack is like a neat pile of cafeteria trays: you only ever add or remove from the top, and it is fast and automatic.

The heap is more like a big warehouse. When you need room for something whose size or lifetime you do not know up front, you ask the warehouse for space, get a slip telling you where it is, and use it for as long as you need — then you, or a cleaner, must give it back.

  1. New call — tray on top.
    THE STACK new
    1

    The stack is a pile of cafeteria trays: each call drops a frame on top.

  2. Done — off it comes.
    RETURN
    2

    When a call returns, its tray pops off and that space is instantly free again.

  3. Stack too deep — overflow!
    just bump a pointer overflow!
    3

    It’s fast because allocating is just nudging a pointer up. But the pile is small.

  4. Space for this? Here’s the slot.
    THE HEAP slip
    4

    The heap is a warehouse: ask for room and you get a slip telling you where it sits.

  5. Follow the slip to the shelf.
    ref on the stack data on the heap
    5

    You reach the data through that reference. It can outlive the call that made it.

  6. Give it back, or it leaks.
    free
    6

    But borrowed space must come back — freed by hand, or swept by a garbage collector.

A neat pile of trays you add and remove from the top, versus a warehouse you borrow space from and must return.

Why the stack is so fast

Each function call pushes a frame holding its locals and where to return to; when it returns, the frame is popped and that space is instantly reusable. Allocation is just bumping a pointer, so there is nothing to search for and nothing to clean up.

The catch is that the stack is small and its data only lives as long as the call that owns it. Return from a function and its stack data is gone.

Why the heap exists

Some data has to outlive the function that made it, or its size is not known until the program runs — a list that grows, an object handed back to a caller. That goes on the heap, reached through a reference.

The price is management: heap space must be released, either manually (and forgetting causes a leak) or by a garbage collector that does it for you at some background cost.

The real version Stack frame simulator →
Found this useful?