What is the difference between the stack and the heap in C++?
The stack holds local variables and function call frames. Allocation is a single register adjustment, so it is extremely fast; deallocation is automatic when scope ends. It is contiguous and cache-friendly. The limits are that its size is fixed at thread creation — typically one to eight megabytes — and that the size must be known at compile time.
The heap is memory obtained with new or malloc. It is large, sized at runtime, and outlives the scope that created it. The costs are a much slower allocator that must search for a free block, potential fragmentation, worse locality, and the obligation to free it.
How to choose: prefer the stack. Use the heap when the object is too large for the stack, when its size is only known at runtime, or when it must outlive the current scope. Even then, own it with unique_ptr or a container rather than a raw pointer.
The failure modes differ: exhausting the stack — usually via unbounded recursion or a huge local array — gives you a stack overflow and immediate crash. Exhausting the heap throws std::bad_alloc. Forgetting to free heap memory leaks; freeing twice or using after free is undefined behaviour and often exploitable.
Note: std::vector is a useful illustration — the vector object itself sits on the stack while its elements live on the heap, and its destructor frees them automatically.





