Stack vs Heap Memory: Differences Explained

A running program uses two main regions of memory for its data. The stack holds function call frames: local variables, arguments and return addresses. It is managed automatically and is very fast, but small and tied to the lifetime of each function call. The heap holds memory that the program requests explicitly, such as with malloc or new, and it lives until it is freed. The heap is flexible and large but slower, and it is where leaks and fragmentation happen.

AspectStackHeap
Used forFunction call frames: local variables, arguments, return addressesDynamically allocated data that must outlive a function or whose size is not known in advance
AllocationAutomatic: the stack pointer moves on each call and returnExplicit: malloc and free, new and delete, or a garbage collector
SpeedVery fast: just adjusting a pointerSlower: the allocator must find a free block and keep records
LifetimeUntil the function returnsUntil the memory is freed (or garbage collected)
SizeLimited (typically a few megabytes per thread)Limited only by the available memory
LayoutUsually grows downward from high addressesUsually grows upward from lower addresses, so the two grow toward each other
FragmentationNonePossible: repeated allocation and freeing can leave unusable gaps
ThreadsEach thread has its own private stackShared by all threads, so the allocator must be thread-safe
Typical errorsStack overflow from deep recursion or large local arraysMemory leaks, use after free, double free and running out of memory

Figures are typical orders of magnitude and vary by process generation and product.

When to use which

Stack
For small, short-lived data whose size is known at compile time: ordinary local variables.
Heap
For large data, data whose size changes at run time, and data that must outlive the function that created it.

FAQ

Why is stack allocation faster than heap allocation?

Stack allocation only moves the stack pointer, while heap allocation must find a free block and update the records of the allocator.

What causes a stack overflow?

Using too much stack, typically through deep or infinite recursion or very large local arrays, which exceeds the stack size limit and crashes the program.

What is a memory leak?

Heap memory that was allocated but never freed, so it cannot be reused. Repeated leaks make a program use more and more memory.

Do threads share the stack?

No. Each thread has its own stack, while all threads share the heap.

Check your understanding

What is the advantage of laying out the heap and stack so they grow in opposite directions with a large gap between them?

  1. AThe gap can be shared flexibly even when it is unknown in advance how much each will use
  2. BBoth can use the same addresses at once, doubling memory
  3. CThe stack can never overflow
Show answer and explanation

Answer: A. The gap can be shared flexibly even when it is unknown in advance how much each will use

Because the heap grows up and the stack grows down, the gap between them serves a program that uses lots of heap as well as one that uses lots of stack. Giving each a fixed size could let one overflow while the other has room to spare. The stack usually has a set limit, though, and recursion that is too deep exceeds it and causes a stack overflow.

Memory allocated with C's malloc generally comes from which area of a process?

  1. AThe .text section
  2. BThe heap
  3. CThe .rodata section
Show answer and explanation

Answer: B. The heap

The heap is the area from which a running program obtains memory of the size it needs and returns it with free when done. Its key feature is that sizes and lifetimes are decided at run time. malloc manages free space itself and asks the OS to enlarge the area when it runs short (through the brk or mmap system calls on Linux). Forgetting to call free leaves unused memory behind, which is a memory leak.

Which lists the typical memory layout of a process on Linux and similar systems from low to high addresses?

  1. AText → data → BSS → heap → (free space) → stack
  2. BStack → text → heap → data → BSS
  3. CHeap → stack → BSS → data → text
Show answer and explanation

Answer: A. Text → data → BSS → heap → (free space) → stack

In a typical layout, from low addresses up come the text (machine code), the initialized data and the zero-initialized BSS, with the heap above them growing toward higher addresses. The stack grows downward from the high end, and shared libraries and mmap regions are placed in the large gap between them. For security, ASLR shifts the actual addresses on every run.

  1. When recursion goes so deep that it exceeds the stack limit, what generally happens on Linux and similar systems?
  2. After repeated malloc and free, a large block may become impossible to allocate even though total free memory is sufficient. What is this phenomenon called?
  3. In RISC-V, what happens if a recursive function (one that calls itself) forgets to save ra on the stack?

Practice Linkers, Loaders & Executables questions

Key terms explained

Stack frame
The area reserved on the stack each time a function is called. It holds the return address, saved registers and local variables and is freed when the function returns.
Stack pointer
The register that points to the current top of the stack; sp (x2) in RISC-V. In many ISAs the stack grows toward lower addresses.
Heap memory
The area from which a running program obtains memory of any size with malloc and the like and returns it with free. Repeated allocation and release can cause fragmentation.

Related comparisons