Heap vs Stack

Is the Heap the Same as the Stack?

No, the heap and the stack are separate memory areas with different rules. The stack is automatic and last in, first out, while the heap is managed by you.

On this page
  1. Separate areas with different rules
  2. Comparison
  3. Both in one example
  4. The C++ standard describes storage durations
  5. Which one to reach for

Separate areas with different rules

The heap and the stack are different regions of memory, and a C++ program uses each in its own way. Both live in RAM, but they follow different rules. The stack holds automatic variables, which are created and destroyed with their scope. The heap holds memory you request with new or malloc and free yourself.

Comparison

Aspect Stack Heap
Who manages it The compiler and runtime, based on scope You, with new and delete or malloc and free
When memory is released When the scope ends When you release it
Order Last in, first out No fixed order
Typical speed Usually faster Usually slower
Typical size Smaller Larger
Common errors Stack overflow, pointers to local variables Leaks, double deletes, dangling pointers

Both in one example

#include <iostream>

int main()
{
    int onStack = 10;            // automatic storage, usually on the stack
    int* onHeap = new int(20);   // dynamic storage, on the heap

    std::cout << onStack << " " << *onHeap << "\n";   // prints 10 20

    delete onHeap;               // you release the heap memory
    return 0;                    // onStack is released here automatically
}

Two things are in this program. onStack is an ordinary local variable. onHeap is also a local variable, so the pointer itself lives in the stack frame, but the integer it points to lives on the heap. Only delete releases that integer. Forgetting the delete would leak it, even though the pointer goes away when main returns.

The C++ standard describes storage durations

The standard speaks of storage durations rather than stack and heap. Local variables have automatic storage duration. Objects created with new have dynamic storage duration. How those objects are laid out in memory is up to the compiler and runtime. A compiler may keep a local variable in a register, and it can reuse memory in ways that don’t show in the source code.

Which one to reach for

  • Use stack variables by default. They are simpler, and they are cleaned up for you.
  • Use the heap when the size or lifetime is only known at runtime.
  • Prefer containers such as std::vector and smart pointers such as std::unique_ptr over raw new and delete.

For the full comparison, read about c heap vs stack.

The complete guide to heap vs stack

Heap vs Stack Memory in C++
Read the guide

Keep exploring

Guides from other topics

All topics →