factorial calls itself. Each call gets its own frame with its own n.
Each call has its own frame and its own variables
Level 3 of 13 · interactive GDB exercise · runs in your browser
Read a backtrace, select an outer frame, and see that every active call has separate copies of its parameters and locals.
backtrace lists the frames. up and down choose which one you look at. The program itself does not move.
Pause in the call where n == 1, then peek at an outer frame.
You work in a real GDB session on the program below. GDB has loaded the program. Nothing is running yet.
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1;
}
int rest = factorial(n - 1);
return n * rest;
}
int main(void) {
int result = factorial(4);
printf("4! = %d\n", result);
return 0;
}
main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.
break <where>break <where> if <cond>backtraceframe <n>, up, downinfo argsprint <expr>continuefinishup to continue execution or return from the function. up/down/frame only change what you inspect. Use finish to actually return.factorial call (n == 4), where the stack is still shallow. continue until n is 1, or delete the breakpoint and add a condition.rest in an outer frame as a meaningful number. It has not been assigned in that call yet. Its bytes are leftovers.