CodePark/ questions / Memory, stack & heap
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Memory, stack & heap

What is the difference between the stack and the heap?

The stack holds function call frames, and the heap holds data with a flexible size or lifetime.

The stack

  • It holds local variables, arguments and return addresses.
  • Each thread has its own stack.
  • Allocating on it only moves the stack pointer, so it's very fast.
  • Its memory is freed automatically when the function returns.
  • It is small and limited in size, often 8 MB for the main thread on Linux. Deep or infinite recursion fills it up. This is a stack overflow.

The heap

  • It holds data whose size or lifetime isn't known in advance, or data that must live longer than the function that created it.
  • All threads of the process share it.
  • It can grow much larger than the stack.
  • Allocation is slower, because an allocator has to find free space.
  • It is freed by hand with free(), or by a garbage collector.

In JavaScript, V8 keeps objects, arrays and closures on its garbage-collected heap. The call stack holds the frames. Infinite recursion ends in RangeError: Maximum call stack size exceeded.

  • The stack holds call frames, one stack per thread. It is fast and freed automatically on return.
  • The stack is small and limited, so deep recursion overflows it.
  • The heap holds dynamic data with a flexible lifetime, and all threads share it.
  • The heap is freed by hand or by a garbage collector.