Sub topic 3
What Happens on the Call Stack
This chapter assumes you can write and call functions, and that you have read the previous chapter on base cases and recursive cases. The examples are in Python 3. The ideas apply to most mainstream languages.
A recursive function calls itself, yet each call still has its own value of n. The call stack is what makes that possible. Once you have a clear model of the stack, most recursion bugs are easy to explain, and so are most of the costs that come up later in this tutorial.
The call stack in one paragraph
The call stack is a last-in, first-out region of memory that the runtime uses to track active function calls. Each time a function is called, the runtime pushes a stack frame (also called an activation record) for that call. When the call returns, its frame is popped and control goes back to the frame underneath. Only the frame on top is running. Every frame below it is paused, waiting for the call it made to finish.
Recursion adds nothing special to this mechanism. A call from factorial to factorial gets a new frame, exactly like a call from main to print.
What a frame holds
| Part of the frame | What it contains | Why recursion needs it |
|---|---|---|
| Arguments | The values passed to this call, such as `n = 3` | Each level works on a different subproblem |
| Local variables | Names assigned inside the function body | Locals in one call never overwrite another call's locals |
| Return address | The point in the caller where execution resumes | The caller can finish its pending work, such as `n * ...` |
| Temporaries | Partly evaluated expressions | `n` is held while `factorial(n - 1)` runs |
The return address and the temporaries are the parts people forget. In return n * factorial(n - 1), the multiplication has not happened yet when the inner call starts. The caller's frame has to remember both n and the fact that a multiplication is still pending. That pending work is the reason recursion uses memory in proportion to its depth.
Watching frames being pushed and popped
The program below counts how many factorial frames are live at each moment, using inspect.stack(), which returns the frames currently on the stack.
import inspect
def live_factorial_frames():
return sum(1 for f in inspect.stack() if f.function == "factorial")
def factorial(n):
live = live_factorial_frames()
indent = " " * (live - 1)
print(f"{indent}push factorial({n}) [{live} frame(s) live]")
if n == 0:
result = 1
else:
result = n * factorial(n - 1)
print(f"{indent}pop factorial({n}) -> {result}")
return result
factorial(3)Output:
push factorial(3) [1 frame(s) live]
push factorial(2) [2 frame(s) live]
push factorial(1) [3 frame(s) live]
push factorial(0) [4 frame(s) live]
pop factorial(0) -> 1
pop factorial(1) -> 1
pop factorial(2) -> 2
pop factorial(3) -> 6Two phases are visible here. During the winding phase, frames pile up and no multiplication has happened. During the unwinding phase, each frame receives a value from the frame above it, does its pending multiplication, and pops. The answer 6 is assembled on the way back down, not on the way up.
Inspecting the paused frames
Each paused frame keeps its own locals and the line where it stopped. You can walk the stack yourself with sys._getframe, which returns the current frame. Each frame's f_back attribute points to its caller's frame.
import sys
def show_stack():
frame = sys._getframe(1) # skip show_stack's own frame
while frame is not None:
if frame.f_code.co_name == "countdown":
print(f"countdown frame: n={frame.f_locals['n']}, paused at line {frame.f_lineno}")
frame = frame.f_back
def countdown(n):
if n == 0:
show_stack()
return
countdown(n - 1)
countdown(3)The output lists the innermost frame first. It has n=0 and is paused on the show_stack() line. Below it are frames with n=1, n=2, and n=3, all paused on the countdown(n - 1) line. Four separate variables named n exist at once, one per frame. The line numbers show the return addresses: every outer frame will resume right after its recursive call.
A loop uses one frame
Compare the iterative version from the earlier chapter on loops:
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iterative(3)) # 6This function runs in a single frame no matter how large n is. The loop overwrites result and i on every pass, so it keeps no history. Recursion keeps one frame per level, and each frame holds the history of what still needs doing. That is the core trade: recursion lets the runtime remember the pending work for you, and you pay for it with one frame per level of depth. Later chapters measure this cost and show what happens when the stack runs out of room.
Common errors explained by the stack model
Forgetting to return the recursive result
def sum_list(xs):
if not xs:
return 0
xs[0] + sum_list(xs[1:]) # bug: result is computed, then discarded
print(sum_list([5])) # None
try:
print(sum_list([1, 2, 3]))
except TypeError as e:
print("TypeError:", e)The frame for [5] receives 0 from the frame above, computes 5 + 0, throws the result away, and falls off the end of the function, so it returns None. With [1, 2, 3], the frame for [3] returns None. The frame for [2, 3] then evaluates 2 + None, which raises TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. The value a frame computes reaches its caller only through return. The fix is return xs[0] + sum_list(xs[1:]).
Expecting a callee to change the caller's local variable
Assigning to a parameter inside a recursive call rebinds the name in that call's frame only. If the inner call does count = count + 1, the outer frame's count stays the same. To pass information back to the caller, return it. To pass it forward to the callee, use an argument. The chapter on accumulators builds on the second option.
Sharing a mutable object across frames by accident
Frames have separate names, but those names can point to the same object. A mutable default argument such as def collect(node, out=[]) creates one list when the function is defined. Every frame, and every later top-level call, then appends to that one list. Use out=None and create a new list inside the function when out is None, or pass the list explicitly. Sharing one object on purpose is fine. The tree-traversal code later in this tutorial passes a single out list down through every call.
Misreading the order of side effects
Code placed before the recursive call runs while the stack winds. Code placed after it runs while the stack unwinds, in reverse order. Move the print in countdown from before the recursive call to after it, and the numbers print in the opposite order. When output appears "backwards," check which side of the call the statement sits on.
How much stack a call uses
The stack space used by a recursive function equals its maximum depth, the largest number of its frames live at the same time, multiplied by the size of a frame. It is not the total number of calls. A function that makes a thousand calls but never goes more than ten deep needs only ten frames at any moment. This difference matters when functions make more than one recursive call, which a later chapter covers. For factorial(n), the depth is n + 1, so its stack use is O(n), while the loop's is O(1).
Exercise
For factorial(4) written recursively, how many factorial frames are live at the moment the base case returns, and which pending operation does each of the other frames hold?
Show answer
Five frames are live: n = 4, 3, 2, 1, 0. The n=0 frame is returning 1. The n=1 frame is holding "1 ?", n=2 is holding "2 ?", n=3 is holding "3 ?", and n=4 is holding "4 ?". Each pending multiplication completes as the frame above it returns.
Exercise
In the countdown function, move the recursive call above a print statement so the body becomes: if n == 0: return; then countdown(n - 1); then print(n). What does countdown(3) print, and why?
Show answer
It prints 1, 2, 3, each on its own line. No print runs while the stack winds. The n=0 frame returns without printing. Then each frame prints its own n after its recursive call returns, so the innermost non-base frame (n=1) prints first and the outermost (n=3) prints last.
Exercise
A recursive function visits every node of a balanced binary tree with 1,023 nodes (10 levels). It makes 1,023 calls in total. Roughly how many of its frames are on the stack at most, and why is that different from 1,023?
Show answer
About 10 or 11, which is the height of the tree plus possibly one frame for a None child. Frames are popped when each call returns, so only the calls on the current root-to-node path are live at once. Stack use depends on maximum depth, not on the total number of calls.