What is the difference between stack and heap memory in C++?
The stack stores local variables and function calls, is very fast, and is freed automatically when a function returns. The heap is memory you allocate manually with new, is larger, lives until you free it with delete, and is slower to allocate. Stack memory is managed for you, while heap memory is your responsibility.
- The stack stores local variables, is fast, and frees automatically when a function returns.
- The heap is allocated with new, is larger and flexible, but must be freed manually.
- Prefer stack allocation and smart pointers to avoid manual heap management.
Stack memory
Local variables live here. They are created when a function starts and destroyed when it returns, all handled automatically. The stack is fast but limited in size, so very deep recursion can overflow it.
Heap memory
You allocate heap memory with new and it stays until you delete it. It is bigger and flexible but slower, and forgetting to free it causes leaks.
int a = 5; // stack, auto freed
int* b = new int(5); // heap, you must delete
delete b;
Summarise as stack is fast and automatic but small, heap is large and flexible but manual. Adding that you prefer stack allocation and smart pointers to avoid manual heap management reflects modern C++ style.
Frequently asked questions
Why is heap allocation slower than stack?
The stack just moves a pointer to allocate, while the heap must search for a suitable free block and track it, which takes more work.
What causes a stack overflow in C++?
Usually very deep or infinite recursion, or allocating very large local arrays, which exhausts the limited stack space.
Common follow up questions
Related interview questions
Want the full C++ guide?
Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the C++ guide All C++ questions