Who changed this?

This program prints 105, but it should print 140. Something changes balance behind your back.

Watchpoints stop on data changes instead of code locations

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

Start this exercise

What you will learn

Use a watchpoint to find the statement that modifies a variable when you do not know where to put a breakpoint.

watch balance pauses whenever its value changes, wherever that happens. Then keep typing continue.

The exercise

Find the function that secretly resets balance.

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 balance = 100;

void deposit(int amount) {
    balance += amount;
}

void apply_fee(void) {
    balance -= 15;
}

void audit(int *account) {
    if (*account > 100) {
        *account = 100;
    }
}

int main(void) {
    deposit(50);
    apply_fee();
    audit(&balance);
    deposit(5);
    printf("balance = %d (expected 140)\n", balance);
    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

watch <expr>
Stop whenever the value of an expression changes.
continue
Resume until the next breakpoint or exit (c).
backtrace
List the active function calls, innermost first (bt).
info breakpoints
List breakpoints and watchpoints (i b).
delete [n]
Remove breakpoint or watchpoint number n for good (d 1). With no number: remove them all.
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).

Common mistakes

Try it in your browser