What is the Stack

The stack is a region of memory that stores function call data in last-in, first-out (LIFO) order. Every time you call a function, a new stack frame is pushed on top. When the function returns, its frame is popped off. This is how your program keeps track of where it is and what it was doing before.

How it works

Each stack frame contains:

  • Local variables — the variables declared inside the function.
  • Return address — where execution should resume when this function finishes.
  • Arguments — the values passed to the function.
  • Saved registers — CPU state that the caller needs restored.

The stack grows and shrinks automatically. Allocation is instant — the CPU just moves the stack pointer. Deallocation is equally fast — move it back. There's no allocator to manage, no fragmentation to worry about.

But the stack has limits. On most systems, each thread gets a fixed-size stack, typically between 1 and 8 megabytes. If your function calls go too deep (deeply recursive algorithms, for instance), you hit a stack overflow and the program crashes.

The stack is also strictly scoped. You cannot return a pointer to a local variable — once the function returns, its stack frame is gone. Data that needs to outlive a function call must go on the heap.

Why it matters

The stack is why function calls work at all. Every time you write a function that calls another function that calls another, the stack is tracking the chain. Each thread gets its own stack, which is why threads can execute different functions independently while sharing everything else.

Understanding the stack also explains common bugs: stack overflows from unbounded recursion, dangling pointers to local variables, and why large arrays should be heap-allocated instead.

See How Memory Works for how the stack fits alongside the heap and virtual memory.

Prerequisites