A debugger lets you stop the program, look at the values, and walk through the code line by line. That is a very different thing from adding print statements, because it tells you what the program was thinking at the moment that it went wrong, and it lets you change nothing while you look.
This is the first lesson in the Building Real Programs module, and the next lesson in this module is about "How Do You Write Tests That Catch Real Bugs?".
Building with debug information
The first step is to build with the debug symbols and with no optimisation, because the optimiser moves the code around and the line numbers stop matching the source.
# build with debug symbols and no optimisation
g++ -std=c++17 -Wall -Wextra -g -O0 main.cpp -o inventory
# run it under the debugger
gdb ./inventoryBreakpoints and stepping
Inside the debugger, the essential commands are few.
(gdb) break Inventory::add_item set a breakpoint on a function
(gdb) break inventory.cpp:42 set a breakpoint on a line
(gdb) run start the program
(gdb) next execute the next line, skipping into calls
(gdb) step execute the next line, entering calls
(gdb) continue run until the next breakpoint
(gdb) print item.sku show the value of a variable
(gdb) backtrace show the call stack
(gdb) quit leave the debuggerAnd the difference between the next and the step is the one that beginners get wrong. The next runs the whole of the next line, including the calls inside it. The step goes into the calls, so you end up inside the function that the line called.
Watching values as they change
A watch expression is re-evaluated every time that the program stops, and that is how you catch the moment that a value becomes wrong instead of the moment that you notice it.
#include <iostream>
#include <string>
#include <vector>
struct Item {
std::string sku;
int quantity;
};
int main() {
std::vector<Item> stock = {{"A-100", 5}, {"B-200", 3}};
int adjustments[3] = {2, -10, 4};
for (int i = 0; i < 3; ++i) {
for (Item& item : stock) {
item.quantity += adjustments[i];
}
std::cout << "after adjustment " << i << '\n';
}
for (const Item& item : stock) {
std::cout << item.sku << ' ' << item.quantity << '\n';
}
return 0;
}The output shows what happens when the adjustments are applied one at a time.
after adjustment 0
after adjustment 1
after adjustment 2
A-100 1
B-200 -1The sanitizers find what a debugger cannot
The sanitizers find the bugs that you were not looking for, and they report them with the exact line.
# address sanitizer: out-of-bounds, use-after-free, double free
g++ -std=c++17 -Wall -Wextra -g -fsanitize=address main.cpp -o inventory_asan
# undefined behaviour sanitizer: signed overflow, bad shifts, misaligned access
g++ -std=c++17 -Wall -Wextra -g -fsanitize=undefined main.cpp -o inventory_ubsan
# both at once, plus leak detection
g++ -std=c++17 -Wall -Wextra -g -fsanitize=address,undefined main.cpp -o inventory_sanAnd when it finds a problem, it prints the file, the line and the stack trace, and then it aborts.
#include <iostream>
#include <vector>
int main() {
std::vector<int> values = {1, 2, 3};
std::cout << "reading past the end\n";
std::cout << values[7] << '\n';
return 0;
}And the same idea applies to the memory. The address sanitizer reports the leaks at the exit, and it names the place where the allocation happened rather than the place where it was lost.
Core dumps and post-mortem debugging
If a program crashes in the production, then the shell can be asked to write a core dump, and the debugger can then open it and show you where the program was.
ulimit -c unlimited
./inventory
gdb ./inventory coreDebugging checklist
- Build with the
-gflag and with the-O0optimisation while you are debugging. - Turn the warnings on with
-Wall -Wextra, because many bugs are warnings first. - Reproduce the problem with the smallest input that still shows it.
- Set the breakpoint before the line that you think is wrong, not after it.
- Check the assumptions one at a time, and do not trust the ones that look obvious.
- Run the sanitizers on the failing case, because they often name the line for you.
- Fix the cause and not the symptom, and add a test that fails before the fix.
Quick reference
- You build with the
-gand the-O0while you are debugging. - The
breaksets a breakpoint, thenextsteps over the calls and thestepsteps into them. - The
printshows a value and thebacktraceshows the call stack. - The address sanitizer finds the out-of-bounds, the use-after-free and the double free, and it finds the leaks at the exit.
- The
undefined behavioursanitizer finds the signed overflow and the bad shifts. - You always add a test that fails before the fix and passes after it.
Try it yourself: write a program with an out-of-bounds read and build it with the address sanitizer, and read the report. Then put a breakpoint on the line that it names and look at the values. Finally, fix the bug, add a test that would have caught it, and run the test with the sanitizer on.