Heap vs Stack

Heap vs Stack Memory in C++

Learn how heap and stack memory differ in C++: how each is allocated, how long data lives, the speed and size trade-offs, and common mistakes, with examples.

On this page
  1. Heap vs stack memory at a glance
  2. What the stack does
  3. What the heap does
  4. Lifetime: when memory goes away
  5. Speed and size
  6. Common mistakes
  7. Let the language manage memory
  8. Choosing stack or heap

Heap vs stack memory at a glance

A C++ program keeps its data in several places. The stack and the heap are the two you meet first. The stack holds local variables and the bookkeeping for function calls, and it is managed for you: memory appears when a function starts and goes away when the function ends. The heap holds memory you request while the program runs, with new (or malloc in C). You decide how long it lives, and you must release it.

Aspect Stack Heap
How memory is requested Automatically, when a variable comes into scope Explicitly, with new or malloc
How memory is released Automatically, when the scope ends Explicitly, with delete or free
Order Last in, first out No fixed order
Typical use Local variables and function call data Objects and arrays whose size or lifetime is set at runtime
Speed Usually faster Usually slower
Size Usually smaller Usually larger
Common problems Stack overflow, pointers to local variables Memory leaks, double deletes, dangling pointers

For most small, short-lived values, the stack is the right place, and you don’t have to think about it. Use the heap when the size or lifetime is only known at runtime. Modern C++ code usually avoids calling new and delete directly, and the sections below show the safer tools.

What the stack does

Each function call gets a block of stack memory called a stack frame. The frame holds the function’s parameters and local variables. When the function returns, its frame is removed and the caller carries on from where it stopped. Frames are placed on top of one another, so the most recent call finishes first.

#include <iostream>

void show(int value)
{
    int doubled = value * 2;   // stored in show's stack frame
    std::cout << doubled << "\n";
}                              // doubled is released here

int main()
{
    int number = 21;           // stored in main's stack frame
    show(number);              // prints 42
    return 0;
}

The C++ standard doesn’t use the words “stack” or “heap.” It describes local variables as having automatic storage duration, and memory from new as having dynamic storage duration. Compilers decide how to implement this, and they may keep some values in registers instead.

What the heap does

Heap memory is requested at runtime. You say how much you need, and the runtime finds a free block and gives you its address through a pointer. In C++, new does this and also runs a constructor for class types. delete runs the destructor and then releases the memory.

#include <iostream>

int main()
{
    int* count = new int(0);       // heap: one int, set to 0
    *count = 7;
    std::cout << *count << "\n";   // prints 7
    delete count;                  // release it when you are done
    return 0;
}

C has no new. Its equivalents are malloc and free, declared in <stdlib.h>. malloc returns a null pointer when it cannot get memory, so check the result before you use it. For the difference between NULL and nullptr, read about c null vs nullptr.

Heap memory lasts until you release it. If you lose every pointer to a block without freeing it, the block is leaked. It stays reserved for the life of the process, but nothing in your code can reach it to free it.

Lifetime: when memory goes away

Stack objects are destroyed when the closing brace of their scope is reached, in reverse order of creation. You don’t write any code for that.

Heap objects are destroyed only when you call delete (or free). Reading or writing through a pointer after its memory has been released is undefined behavior, and the program may crash or quietly produce wrong results.

The stack rule causes a classic bug: returning the address of a local variable.

int* makeNumber()
{
    int value = 5;
    return &value;   // wrong: value is released when the function returns
}

Most compilers warn about this code. A caller that uses the returned pointer is reading memory that no longer belongs to value.

Speed and size

Stack allocation usually costs very little: the program moves a stack pointer to make room. A heap allocation has to find a free block, record it, and sometimes ask the operating system for more memory. So heap operations are usually slower. Many small allocations and frees can also leave scattered gaps that are hard to reuse, which is called fragmentation.

The stack is also smaller. Its size is set by the system or the thread, and typical limits are a few megabytes. A local array of ten million int values, about 40 MB with 4-byte integers, is far too large for that. The heap is limited mainly by the memory the system can give the program.

Common mistakes

  • Forgetting delete or free. The memory leaks.
  • Deleting the same block twice. That is undefined behavior.
  • Using a pointer after its memory is released. The pointer is now dangling.
  • Returning a pointer or reference to a local variable. The variable is gone when the function returns.
  • Recursing too deeply. Each call adds a stack frame, and enough frames overflow the stack.

Base cases are what stop a recursion before that happens, and recursive function in c covers them. Many of these mistakes end in a crash, often reported as a segmentation fault. Tools such as Valgrind can report leaks and invalid memory use while you test. For the setup steps, see how to use valgrind in c.

Let the language manage memory

Modern C++ gives you types that use the heap and clean up after themselves. These are usually a safer first choice than raw new and delete.

  • std::vector and std::string usually keep their elements or characters on the heap, and they release that memory in their destructors. Short strings may be stored inside the string object instead. For the common ways to start a vector, read about c vector initialization.
  • std::unique_ptr owns a single heap object and deletes it when it goes out of scope.
  • std::shared_ptr lets several owners share one heap object, and it frees the object after the last owner lets go.
#include <iostream>
#include <memory>

int main()
{
    auto value = std::make_unique<int>(99);   // heap memory, owned by value
    std::cout << *value << "\n";              // prints 99
    return 0;                                 // the int is freed here
}

std::make_unique needs C++14 or later.

Choosing stack or heap

  • Use the stack for small values that live inside one function, such as counters, loop variables and small objects.
  • Use the heap when the size is only known at runtime, or when an object must outlive the function that created it.
  • Prefer containers and smart pointers to raw new and delete.

Each thread has its own stack, so local variables belong to the thread that runs them. Data shared between threads needs more care, and you can read about concurrency in c for ways to share it safely.

In short, the stack is automatic and fast but limited in size. The heap is flexible and large, but you manage it yourself unless a container or smart pointer does that work for you.

Keep exploring

Guides from other topics

All topics →

std::list in C++

std::list is the C++ standard library's doubly linked list. Learn to create one, add and remove elements, loop through it, and when to pick it over a vector.

std::list 5 min read