Memory & Pointers

the call stack

Functions call other functions, which call still more — and each call must remember where to come back to and keep its own private workspace. The call stack is the region of memory that bookkeeps all of this. Think of a stack of plates: every function call adds a plate on top, and when a function finishes, its plate comes off — last on, first off.

Each call pushes a stack frame onto the stack: a block holding that call's local variables, its arguments, and the return address that says where to resume in the caller. The CPU tracks the top with a stack pointer register (rsp on x86-64); calling a function moves the stack pointer to make room and returning moves it back. Because the most recently called function is always the one to finish first, this last-in-first-out discipline matches how nested calls unwind exactly. On most systems the stack grows downward — toward lower addresses — so 'pushing' a frame actually subtracts from the stack pointer.

Two honest points. First, 'the stack' here is a region of process memory that grows and shrinks with calls — keep it distinct from the stack data structure (the abstract last-in-first-out container); the region is named after the discipline it follows. Second, the stack is finite (often a few megabytes), so unbounded recursion or a huge local array can run off the end and cause a stack overflow, typically reported as a crash. Stack memory is fast and automatically reclaimed on return, which is exactly why returning a pointer to a local is a bug.

main() calls f(), f() calls g(): the stack holds three frames, with g's on top. When g returns its frame is popped (the stack pointer moves back up), control resumes in f at g's return address, and so on back to main.

Frames stack up as calls nest and pop off as they return — last in, first out.

The call stack (a region of memory) is not the stack data structure (an abstract LIFO container) — the region is just named after the LIFO discipline it follows. The stack is finite; runaway recursion overflows it. Memory there is reclaimed automatically on return, so a pointer to a local goes dangling the instant the function exits.

Also called
the stackexecution stack呼叫堆疊