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
- Stack Allocation
- Heap Allocation with new/delete
- Object Lifetime
- Common Memory Bugs