The call stack

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

Start this exercise

What you will learn

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.

The exercise

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.

GDB commands you will use

break <where>
Stop when execution reaches a function or line (b main, b 12).
break <where> if <cond>
Conditional breakpoint, e.g. break factorial if n == 1.
backtrace
List the active function calls, innermost first (bt).
frame <n>, up, down
Select a frame to inspect. Does not move execution.
info args
Show the selected frame's arguments.
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
continue
Resume until the next breakpoint or exit (c).
finish
Run until the current function returns; shows the return value.

Common mistakes

Try it in your browser