C++ › Memory Management

What is the difference between the stack and the heap?

Beginner

Answer

The stack is a region of memory for automatic (local) variables, managed by the compiler with LIFO allocation and fast, deterministic lifetime tied to scope. The heap (free store) is for dynamic allocation via new/malloc, managed manually (or by smart pointers), with flexible lifetime but slower allocation and risk of leaks.
void f() {
    int a = 10;          // stack
    int* p = new int(20); // heap
    delete p;            // must free heap memory
}
Real-world example Local loop counters live on the stack; a dynamically sized buffer is allocated on the heap.

Common follow-ups: Which is faster to allocate? | Who frees heap memory?