Processes & the Process Abstraction

the stack

Picture a stack of cafeteria trays by the door: you add a tray on top when you enter a step, and you remove the top tray when you leave it, always last-in, first-out. Each function call in a running program works like adding a tray. The stack is the region of a process's memory that records the chain of active function calls, with each call's local variables, parameters, and return address stacked on top.

When a function is called, the program pushes a stack frame onto the stack: a block holding that call's parameters, its local variables, and the return address telling the CPU where to resume when the function finishes. When the function returns, its frame is popped off, automatically freeing those locals, and execution continues from the saved return address. Because calls nest and return in strict last-in, first-out order, the stack grows and shrinks cleanly with no fragmentation. In the classic layout the stack sits at the high end of the address space and grows downward, toward the upward-growing heap, so the two share the empty middle.

The stack is fast and automatic, which is why local variables are cheap, but it is also limited and rigid. Frames must be freed in the reverse order they were created, so the stack cannot hold data that must outlive its function (that is the heap's job). Two classic failures: a stack overflow, when too-deep recursion or a huge local array pushes the stack past its limit (often into the heap or a guard page) and the program crashes; and a dangling pointer, when code returns the address of a local variable whose frame has already been popped.

main calls f, which calls g. The stack holds three frames (main, then f on top, then g on top). When g returns, its frame is popped and its locals vanish; then f returns and its frame is popped too.

Last-in, first-out: the most recent call is on top and returns first.

Never return a pointer to a local variable. Its stack frame is popped when the function returns, so the pointer dangles and using it is undefined behavior.

Also called
call stackexecution stack堆疊呼叫堆疊