0Pricing
C++ Academy · Lesson

Stack Allocation

How automatic storage works.

Automatic Storage

Local variables live in automatic storage, commonly called the stack. They are created when execution enters their scope and destroyed when it leaves.

#include <iostream>

int main() {
    int x = 42;          // on the stack
    double pi = 3.14;    // on the stack
    std::cout << x << " " << pi << "\n";
}

The Stack Grows and Shrinks

Each function call pushes a stack frame holding its local variables. When the function returns, the frame is popped and the locals vanish — no manual cleanup needed.

#include <iostream>

void greet() {
    int local = 7;          // pushed on call
    std::cout << local << "\n";
}                            // popped on return

int main() { greet(); }

All lessons in this course

  1. Stack Allocation
  2. Heap Allocation with new/delete
  3. Object Lifetime
  4. Common Memory Bugs
← Back to C++ Academy