What is the difference between the stack and the heap?
Both are regions of memory a program uses, with fundamentally different allocation strategies and lifetimes.
The stack holds function call frames. Each call pushes a frame containing parameters, local variables and the return address; each return pops it. Allocation is automatic and extremely fast — it is essentially moving a pointer — and deallocation is guaranteed by the structure itself.
Properties: strictly last-in-first-out, contiguous, excellent cache locality, and a fixed, fairly small size (often a few megabytes per thread).
Its limits: everything must have a size known at compile time, and lifetimes are bound to the call. Returning a pointer to a local variable is a classic bug in C, because the frame is gone. Exceed the stack — usually through unbounded recursion — and you get a stack overflow.
The heap holds dynamically allocated memory. You request a block at runtime, of a size determined at runtime, and it lives until explicitly freed or garbage collected.
Properties: large, flexible, and lifetimes independent of function calls — which is what lets you return data structures from functions and share them.
Its costs: allocation is significantly slower, requiring the allocator to find a suitable block; memory becomes fragmented over time; access has worse cache locality because objects are scattered; and it is where memory leaks and use-after-free bugs live.
How languages expose this. In C and C++ it is explicit — locals on the stack, malloc/new on the heap. In Java, primitives and references sit on the stack while objects live on the heap. Go's compiler performs escape analysis, placing values on the stack when it can prove they do not outlive the function. Rust's ownership system tracks heap lifetimes at compile time.
Practical implication: prefer stack allocation where possible — it is faster and cannot leak.