What the call stack does during recursion
A recursive function calls itself, yet each call keeps its own n and picks up exactly where it left off. Here is the stack of frames that makes that work, drawn one push and one pop at a time.
01 A function that calls itself
Here is factorial written the recursive way. fact(3) works out 3 * fact(2), which works out 2 * fact(1), which is just 1.
The puzzle: when fact(1) returns, how does the program know it was in the middle of 2 * …, and that n was 2 there? The inner calls used n too.
02 The wrong picture: one shared n
If there were only one n for the function, each call would overwrite it. By the time fact(1) set n = 1, the 3 and the 2 would be lost, and every multiplication on the way back would use 1.
fact(3): n = 3fact(2): n = 2 (3 is overwritten)fact(1): n = 1 (2 is overwritten)back in fact(2): 1 * 1 = 1back in fact(3): 1 * 1 = 1
fact(3): its own n = 3fact(2): its own n = 2fact(1): its own n = 1back in fact(2): 2 * 1 = 2back in fact(3): 3 * 2 = 6
What really happens is the right-hand side. Every call gets a fresh, private set of variables, kept in a frame.
03 Each call gets its own frame
The frames are kept on the call stack. A call pushes a new frame on top. Only the top frame runs; the ones below are paused mid-line. A return pops the top frame and hands its value to the one below, which carries on.
- frame just pushed
- running again
- paused, waiting
- final answer
Nothing has run yet. The stack is empty, and nothing has been returned.
Last in, first out: fact(1) was pushed last and returned first. That is the whole reason it is a stack.
04 What a frame holds
| Part | In fact(2) | Why it is needed |
|---|---|---|
| Arguments | n = 2 | Each call was passed its own value. |
| Local variables | (none here) | Anything assigned inside the call lives here too. |
| Where to resume | line 4, in the middle of n * … | So the call can carry on after the inner call returns. |
| Who called it | fact(3)'s frame | So the return value goes to the right place. |
In C, Java or Go, frames typically sit in a block of memory each thread reserves for this, also called the stack. CPython keeps its own frame records rather than using the machine stack directly, but they are pushed and popped in exactly the same order.
05 Two calls per frame, one path at a time
fib(n) calls itself twice: fib(n - 1) + fib(n - 2). That looks as if the stack should hold both branches at once. It does not. The left call runs to the end and is popped before the right one starts.
- just called
- running
- on the stack, waiting
- returned
- not called yet
- paused frame
Before the call. The tree shows every call fib(3) will make; none has happened yet.
fib repeats the same calls many times, which is why it is slow, not why it crashes.06 Watch the stack in Python
Pass the depth down and indent by it. Each call line is a push; each returns line is a pop. The returns come out in the reverse order of the calls.
A crash traceback is the same picture, printed for you: one line pair per frame that was on the stack when the error happened, oldest first.
07 When the stack runs out
def fact(n):
return n * fact(n - 1)No base caseNothing ever returns, so frames pile up until the limit. CPython stops at a recursion limit (sys.getrecursionlimit() is 1000 by default) with RecursionError; Java throws StackOverflowError.fact(0)A base case the input never reachesfact(0) goes to -1, -2, … and never hits n == 1. Guard with n <= 1.walk(node.next) # 100,000 nodesCorrect, but too deepRecursing once per item of a long list needs one frame per item. Past a few thousand, use a loop or an explicit stack you manage yourself.def add(x, seen=[]):
seen.append(x)Frames hold names, not copiesEach frame has its own variable names, but they can point at the same list. A change made deep down is visible to every frame that shares it.A deep stack is about depth, not about the number of calls. fib(30) makes over a million calls but is never more than 30 frames deep, so it is slow but does not overflow.