How the stack and the heap differ

· 3 min read

#how-it-works#os

The stack and the heap are two places a program keeps data while it runs. The idea to keep: the stack is orderly and fast but needs a known size, while the heap is flexible but is reached through a pointer.

The short version

The stack holds values in the order it gets them and removes them in the opposite order: last in, first out. Every value on it must have a known, fixed size. Data whose size is unknown at compile time, or can change, goes on the heap instead. There, an allocator finds a free spot big enough, marks it as in use and returns a pointer to it.

Stack and heap side by side The stack on the left holds local variables, a fixed-size pointer and arguments, with push and pop at the top. The pointer leads to the heap on the right, which holds data of any size and is managed by an allocator that finds space and returns an address. Stack (LIFO) local variables pointer (fixed size) arguments push and pop at the top allocator finds space, returns address Heap: data of any size follow the pointer
Simplified: stack values are pushed and popped in order; heap data is reached through a pointer.

Step by step

  1. A function is called, and its arguments and local variables are pushed onto the stack.
  2. Data of unknown or changing size asks the heap for space.
  3. The allocator finds a free spot, marks it in use and returns its address.
  4. A pointer has a fixed size, so it sits on the stack while the data sits on the heap.
  5. When the function ends, its values are popped off the stack. Cleaning up heap data depends on the language: Go uses a garbage collector, Rust uses ownership.
Stack Heap
Order last in, first out no fixed order
Size of each value known and fixed can be unknown or change
Adding data push at the top, no search allocator finds space, returns a pointer
Reading data directly follow a pointer, generally slower

Why it matters

The stack is simple and quick but needs a fixed size; the heap is flexible, but each use costs a search for space and a pointer to follow. Which one a variable lands in is often the language's call: in Go it is an implementation detail, and the compiler moves a variable to the heap when it cannot prove the stack is safe.

Sources