Skip to content
BENIBIX Learn

Stack Memory

Also known as Call Stack, The Stack, Stack Overflow

A small, fast part of memory. It holds the values of running functions.

Think of it like

Think of it like a pile of plates. You add to the top and take from the top.

Example

Lucy's function calls itself with no stopping point. After many thousands of calls the stack is full. The program crashes with a stack overflow.

Why it matters

It is why local values are cheap and vanish after a function ends. It is also why deep recursion can crash.

Definition

Stack memory is a small, fast area that holds the values of the functions running now. Each call to a function puts a new block on top of the stack. The block holds that function's local variables. When the function returns, its block comes off the top at once. On Linux the stack for a program's main thread is usually 8 MB. So a function that calls too deep causes a stack overflow.

Example code

console
$ ulimit -s
8192
On this Linux machine, each program's main stack can grow to 8,192 KB, or 8 MB.

Common mistake

Putting a huge array in a local variable in C. It may not fit on the stack, so it belongs on the heap.

Key takeaways

  1. 1
    Last in, first out. Like a pile of plates.
  2. 2
    Freed on return. Nothing to clean up.
  3. 3
    Small and fast. Often 8 MB on Linux.

Compare