C++20 sections · 1024 units
Open in Course

Stack vs Heap

Memory layout

C++ programs use two memory regions: stack and heap. Stack stores local variables, grows/shrinks automatically. Heap stores manually allocated data, persists until you free it. Stack is fast but limited (typically 1-8 MB).

Heap is slower but much larger, letting you allocate gigabytes if needed. You'll choose stack for small, short-lived data and heap for large structures or runtime-sized collections.