Explain the difference between the stack and the heap. When would you prefer one over the other?
Last updated
The stack is fast, automatically managed memory for local variables with LIFO lifetime; the heap is a larger, manually (or smart-pointer) managed pool for objects whose size or lifetime isn't known at compile time. Prefer the stack for short-lived, fixed-size data and the heap when you need dynamic size or lifetime beyond the current scope.
The stack:
Allocation is just moving a pointer, so it's extremely fast; memory is reclaimed automatically when scope ends.
Limited in size (typically a few MB); deep recursion or huge arrays cause stack overflow.
The heap:
Allocated via
new/malloc; survives until explicitly freed, so it outlives the creating function.Slower (bookkeeping, possible fragmentation) and risks leaks/dangling pointers if mismanaged.
When to prefer which:
Stack: size known at compile time, lifetime confined to the scope.
Heap: large or runtime-sized data, ownership transfer, or lifetime extending past the function; wrap it in
unique_ptr/shared_ptr.