Skip to content
BENIBIX Learn

Stack vs Heap Memory

Stack memory and heap memory are both parts of a running program's memory, but they hold different data. The stack is small and fast. It holds the local values of the functions running now, and they vanish when the function returns. The heap is large and slower. It holds data that must live longer or grow, until it is freed.

Development⚙️ Compilers & Runtimes

Stack Memory

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

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
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.
Full entry
Development⚙️ Compilers & Runtimes

Heap Memory

A big part of memory. Its data can last longer than one function.

Heap memory is a large area for data that must outlive one function call. It also holds data whose size is not known ahead of time, like a list that keeps growing. The program asks for a piece of the heap when it needs one. That piece stays until it is freed, by you in C or by the garbage collector in most other languages. The heap is bigger than the stack but slower to use.

Example
Jack's app loads 10,000 user records into a list. The list is too big and lives too long for the stack, so it goes on the heap.
Why it matters
Almost every object, list and string in a real app lives on the heap. It is where most memory problems happen.
Full entry

In one line

Stack Memory
A small, fast part of memory. It holds the values of running functions.
Heap Memory
A big part of memory. Its data can last longer than one function.