How the stack and the heap differ
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.
Step by step
- A function is called, and its arguments and local variables are pushed onto the stack.
- Data of unknown or changing size asks the heap for space.
- The allocator finds a free spot, marks it in use and returns its address.
- A pointer has a fixed size, so it sits on the stack while the data sits on the heap.
- 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
- What is Ownership? — The Rust Programming Language — last in, first out, fixed size on the stack, allocation and pointers on the heap, push versus allocate, function calls
- Go FAQ — "How do I know whether a variable is allocated on the heap or the stack?": placement is an implementation detail, and the compiler uses the heap when it cannot prove the variable is unused after the function returns