Stack vs heap memory in C++

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

Common follow-up questions

Interview tips

Concepts covered

stack, heap, memory layout, lifetime

More C++ & STL questions