CurriculumStack vs Heap

Stack vs Heap

When a C++ program runs, it uses two main areas of RAM: the Stack and the Heap. The Stack is fast, small, and automatically managed. The Heap is massive, slightly slower, and must be manually managed by you (the programmer).

01The Stack (Automatic Memory)

Whenever you declare a normal variable inside a function, it goes on the Stack.

The stack is a LIFO (Last-In, First-Out) data structure. When a function finishes, all its stack variables are automatically popped off and destroyed. It is incredibly fast.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.

02The Heap (Dynamic Memory)

If you need memory that survives after a function ends, or if you don't know how much memory you need until the program is running, you use the Heap.

You request heap memory using the new keyword. It returns a pointer.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.

03Pointers Bridge the Gap

It's important to realize that the pointer itself lives on the Stack, but the memory it points to lives on the Heap.

They are two separate pieces of memory connected by an address.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.

04Stack Overflow

The Stack is small (typically a few Megabytes). If you try to put too much on it, it literally overflows and the operating system kills your program.

If you uncomment the huge array below, the program will crash.
main.cpp
Loading...
Terminal
Waiting for execution...

05Memory Leak (Heap Danger)

The Heap is massive, but it is dumb. It never cleans itself up. If you allocate memory and lose the pointer to it, that memory is gone forever until the program closes.

This is called a Memory Leak. If a game has a memory leak, it will eventually consume all your RAM and crash.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.
← Back to Curriculum