What if?

GDB can do more than look. set var armor = 2 changes a variable in the paused program.

Changing variables and calling functions from the debugger

Level 11 of 13 · interactive GDB exercise · runs in your browser

Start this exercise

What you will learn

Change a variable in a paused program and call one of its functions, to test an idea without editing or recompiling.

print damage(4) calls a function of the program, right now, and shows what it returns.

Left alone, this program prints health = 60, lives = 2. Make it print something better, without touching the code.

The exercise

Give the player armor before the hit lands, and let the program finish with all 3 lives.

You work in a real GDB session on the program below. A breakpoint on main was set and the program was started; it is paused at the first line of main.

#include <stdio.h>

int lives = 3;

int damage(int armor) {
    return 40 - armor * 10;
}

int main(void) {
    int health = 100;
    int armor = 0;
    health -= damage(armor);
    if (health < 70) {
        lives--;
    }
    printf("health = %d, lives = %d\n", health, lives);
    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

set var <name> = <value>
Change a variable in the paused program (set var armor = 2).
print <var> = <value>
Assigns as well: print evaluates any C expression, including assignments.
call <func>(<args>)
Run one of the program's functions right now and show the result. print func(args) does the same.
return [value]
Leave the current function immediately, skipping the rest of it, optionally with a return value.
next
Run the current line; step over function calls (n).
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).
run
Start the program from the beginning (r).

Common mistakes

Try it in your browser