Recursion and the call stack
Every call gets its own stack frame. Watch factorial build a tower of them, then find the two inputs that break it.
- Trace a recursive function through the frames it pushes and pops
- Predict where a 32-bit int overflows, and choose a type that does not
- Explain why a missing base case ends in a segmentation fault
factorial.c is the textbook recursion:
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
The function cannot finish n * factorial(n - 1) until the inner call returns, so every call stays on the stack, waiting. Only when factorial(0) returns 1 does the tower start to collapse, one multiplication per frame.
13! does not fit
Run the program and the answers look fine until they suddenly do not:
| n | program prints | true n! |
|---|---|---|
| 12 | 479001600 | 479,001,600 |
| 13 | 1932053504 | 6,227,020,800 |
| 17 | −288522240 | 355,687,428,096,000 |
| 20 | −2102132736 | 2,432,902,008,176,640,000 |
A 32-bit int holds at most \(2^{31} - 1 = 2{,}147{,}483{,}647\), and 13! is about three times that. Signed overflow is undefined behaviour in C; on x86 the result wraps modulo \(2^{32}\), which is how 6,227,020,800 becomes 1,932,053,504 and later values turn negative. The compiler is also allowed to assume overflow never happens and optimise accordingly, so the wrapped value is not even guaranteed.
unsigned long long (64 bits) holds up to 20! = 2,432,902,008,176,640,000; 21! wraps there too. Beyond that, a factorial needs a big-integer library — or a logarithm, lgamma(n + 1), when only its size matters.
Negative input never stops
Enter -1 and the program crashes with a segmentation fault. The base case n == 0 is never reached: \(-1, -2, -3, \ldots\) recurse until the frames fill the stack (8 MB by default on Linux) and the next push hits unmapped memory. A guard fixes it:
unsigned long long factorial(int n) {
if (n < 0) return 0; /* or report an error */
unsigned long long r = 1;
for (int k = 2; k <= n; k++) r *= k;
return r;
}
The loop version needs no stack at all. Recursion is the clearest way to state factorial, but a loop is the better way to compute it in C, which does not promise to optimise tail calls away.
Try it yourself. Add printf("%p\n", (void *)&n); at the top of factorial and run it for n = 5. How far apart are consecutive frames, in bytes? Then compile with gcc -fsanitize=undefined and run 13: read the runtime error that names the overflow.