# Stack vs heap memory in C++

> What is the difference between stack and heap memory? How does a C++ program's memory layout look, and when should you use each?

Canonical: https://www.internhack.in/learn/interview/cpp-interview/cpp-stack-vs-heap
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is the difference between stack and heap memory? How does a C++ program's memory layout look, and when should you use each?

## Answer

Every C++ developer needs a mental model of where their objects live, because it decides speed, lifetime, and whole categories of bugs. Let's build that model.

Picture a stack of plates in a canteen. You put a plate on top and you can only remove from the top. That is the call stack. Every time a function is called, a frame is pushed containing its local variables, parameters, and the return address; when the function returns, the frame is popped and everything in it dies automatically. Allocation is nearly free (just move the stack pointer), memory is contiguous and cache-friendly, and lifetime is tied strictly to scope. The catch: the stack is small (often 1 to 8 MB), so huge local arrays or deep recursion cause a stack overflow, and objects cannot outlive their function.

The heap (free store) is more like a large warehouse where you ask a clerk for space. You request memory with new or malloc, and you get a pointer back. The memory lives until you explicitly release it with delete or free, regardless of scope. It is large, limited mostly by system memory, and allows objects whose size is unknown at compile time or that need to outlive the creating function. The cost: allocation is slower because the allocator searches for a block, memory can fragment, access may be less cache friendly, and you must manage lifetime, which is where leaks, double frees and dangling pointers come from.

For the classic process layout, say it top-down: text segment (code), initialised data (globals and statics with values), BSS (zero-initialised globals and statics), the heap that grows upward, and the stack that grows downward. Static and global variables live in the data or BSS segments, not on the stack or heap.

A subtle and frequently tested point: 'int\* p = new int(5);' puts the pointer p on the stack but the int on the heap. Also, std::vector<int> v(1000000) puts only the small vector control block (pointer, size, capacity) on the stack while its million elements live on the heap. Lastly, a std::array<int, 1000000> as a local variable really does sit on the stack and may overflow it.

The modern guidance: prefer stack objects (automatic storage) by default, use containers and smart pointers when you need heap allocation, and never write a bare new unless you have a specific reason. If asked about polymorphism, note that you usually need pointers or references to base classes, which often means heap allocation, but that is a design choice rather than a rule.

## Code examples

### Where things live

```
#include <iostream>
#include <vector>
#include <memory>

int globalCounter = 0;            // data/BSS segment

int* badReturn() {
    int local = 42;               // stack
    return &local;                // dangling: never do this
}

std::unique_ptr<int> goodReturn() {
    return std::make_unique<int>(42);   // heap, freed automatically
}

int main() {
    int onStack = 1;                      // stack
    int arr[1000];                        // stack, 4000 bytes
    std::vector<int> v(1000000);          // control block on stack, data on heap
    auto p = goodReturn();                // pointer on stack, int on heap
    std::cout << sizeof(arr) << " " << v.size() << " " << *p << "\n";
    (void)onStack; (void)badReturn; (void)globalCounter;
}
```

sizeof(arr) is the full array (stack). The vector holds one million ints on the heap. badReturn is shown only as an anti-pattern and never called.

## Key points

- Stack: automatic lifetime, fast, small, LIFO; heap: manual or smart-pointer lifetime, large, slower.
- Locals and function frames live on the stack; new/malloc memory lives on the heap.
- Globals and statics live in the data/BSS segments.
- A vector's elements are on the heap even if the vector object itself is a local.
- Deep recursion or huge local arrays can overflow the stack.

## Common follow-up questions

- What causes a stack overflow and how do you avoid it?
- Where do static local variables live?
- Why is stack allocation faster than heap allocation?

## Interview tips

- Draw the memory layout diagram: text, data, BSS, heap up, stack down.
- Mention the vector example to show you know a local object can own heap memory.

## Concepts covered

stack, heap, memory layout, lifetime

Previous: [const pointer vs pointer to const, and const correctness](https://www.internhack.in/learn/interview/cpp-interview/cpp-const-correctness) · Next: [new/delete vs malloc/free](https://www.internhack.in/learn/interview/cpp-interview/cpp-new-delete-vs-malloc-free) · [All of C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)

## More C++ & STL questions

- [Memory leaks, dangling pointers and double free](https://www.internhack.in/learn/interview/cpp-interview/cpp-memory-leaks-dangling-pointers)
- [RAII: Resource Acquisition Is Initialization](https://www.internhack.in/learn/interview/cpp-interview/cpp-raii)
- [Constructors in C++: default, copy and move](https://www.internhack.in/learn/interview/cpp-interview/cpp-constructors-copy-move)
- [Shallow copy vs deep copy](https://www.internhack.in/learn/interview/cpp-interview/cpp-shallow-vs-deep-copy)
- [Rule of three, rule of five and rule of zero](https://www.internhack.in/learn/interview/cpp-interview/cpp-rule-of-three-five-zero)
- [Lvalues, rvalues and move semantics](https://www.internhack.in/learn/interview/cpp-interview/cpp-lvalue-rvalue-move-semantics)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)
