C8 · Lesson 15 · Recursion and stack frames
Functions that call themselves, one frame at a time
Lesson 14's calling convention is exactly what makes recursion work. Every call gets its own stack frame, a slice of the stack holding its saved return address and whatever values it needs after the next call returns, so each level of a recursive function keeps its own copy of its argument while deeper levels run. Watch the stack pointer as a recursive function runs and you'll see it step down one frame per level, then climb back as the answers combine on the way out.
- A recursive Fibonacci:
fib(n)returns n when n < 2, otherwise fib(n − 1) + fib(n − 2). It's called with n = 6, and t6 counts the calls. - Step it and watch sp. Each call that recurses makes a 16-byte frame holding ra, n and, once the first call returns, fib(n − 1). The stack is never more than five frames deep.
- Run it to the end: a0 = 8 and t6 = 25, so fib(6) took 25 calls although it's only five levels deep. The same small values are worked out again and again.
Predict
A recursive function uses a 16-byte frame per call. Called with n = 1000, it recurses 999 levels deep. How much stack does it need?
About 16 kB: 999 frames of 16 bytes are all live at once at the deepest point. On a small microcontroller with a few kilobytes of RAM that overflows the stack, which is why embedded code avoids deep recursion.
Name it
The stack frame
A non-leaf function (one that calls others) must save ra, since its own call will overwrite it, and any values it needs after the call that live in caller-saved registers (the a and t registers). It also saves any s registers it uses. The usual shape:
f: addi sp, sp, -16 # allocate the frame
sw ra, 12(sp)
sw s0, 8(sp) # save what you'll use
... # body, including calls
lw s0, 8(sp)
lw ra, 12(sp)
addi sp, sp, 16 # free it
ret
The RISC-V convention keeps sp a multiple of 16. A leaf function, which calls nothing, can often skip the frame entirely.
Recursion
Each level's frame holds that level's values, so recursion needs no special support. Its cost is stack: the depth times the frame size, all at once at the deepest point. A tail call (calling as the very last action) can reuse the current frame, so tail recursion compiles to a loop.
Counting calls
Some recursions branch: the naive Fibonacci, , makes calls to compute , exponential in n, although its depth is only n. The same results computed in a loop take n steps.
Worked example
How deep does fib(6) go, and how much stack does it use with 16-byte frames?
Show the solution
- Find the deepest chain. fib(6) → fib(5) → fib(4) → fib(3) → fib(2) → fib(1).
- Count the frames. The first five make frames before calling, and fib(1) returns at once, so there are 5 frames, 80 bytes, at the deepest point.
- Where sp goes. It goes down from 0x10000 to 0xFFB0.
- The other branches. They are shallower and reuse the same stack space.
Answer five frames deep, 80 bytes of stack, with sp going down to 0xFFB0.
Worked example
How many calls does the naive recursive Fibonacci make to compute F(10)?
Show the solution
- Count the calls. With F(11) = 89: to get F(10) = 55.
- A loop instead. A loop that starts from F(0) and F(1) needs 9 additions.
Answer 177 calls, against 9 additions for a loop.
Worked example
A recursive factorial uses a 16-byte frame per call. How much stack does fact(10) need, and what does a loop need?
Show the solution
- Count the live frames. fact(10) calls fact(9) and so on down to fact(1), which returns without recursing: 10 frames are live at the deepest point.
- The stack they use.
- A loop. A loop multiplying a running product needs no frames at all.
- Tail calls. Many compilers turn a recursive call in tail position (the last thing a function does) into a jump, but factorial's multiplication after the call keeps it out of tail position unless it's rewritten with an accumulator.
Answer fact(10) needs 160 bytes of stack, and a loop needs none.
Check
A recursive function with a 16-byte frame is called with n = 100; levels n down to 2 each make a frame before recursing, and level 1 returns at once. How much stack is in use at the deepest point?
Check
How many calls does the naive recursive Fibonacci make to compute F(8)?
Check
With n in a0, leave the Fibonacci number F(n) in a0, where F(0) = 0, F(1) = 1 and each later one is the sum of the two before. (A recursive version or a loop: either is fine.)
RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.
Check
Inside a recursive function, n arrives in a0 and is needed after the recursive call. Where should it be kept across the call?
Check
Which functions must save ra on the stack?
Check
A naive recursive Fibonacci computes F(10) with 16-byte frames.
(a)
How much stack does it use at the deepest point?
(b)
How many additions does a loop need instead?
Check
With n in a0 (at most 12), put n! into a1.
RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.
Explain why
Why does each level of a recursive function keep its own value of n, even though every level uses the same code?
The code is shared, but the data isn't: every call allocates a new stack frame by moving the stack pointer down, and saves its own n there before calling itself. The deeper call makes a frame further down and saves its own, different n. When a call returns it frees only its own frame, so the stack pointer is back exactly where the caller left it, pointing at the caller's frame, and the caller reloads its own n from there. The stack holds one frame per active call, so as many copies of n as there are levels.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.