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
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.
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.
watch <expr>continuebacktraceinfo breakpointsdelete [n]print <expr>run. That restarts the program; it works, but you will stop at main first. Use continue from where you are.delete takes its number, like a breakpoint.continue. Software watchpoints single-step, which takes a moment. The status bar shows running; Interrupt (Ctrl-C) always works.