Objective
"Tell me about a hard bug you fixed" and "the strategy crashes once a week in production; what do you do?" are standard developer questions. The interviewer wants a method, not heroics. By the end of this lesson you should be able to describe that method, use git bisect and a debugger, and explain what each sanitizer finds.
The method
- Reproduce. Get a failing run you can repeat on demand: the captured market data, the config, the binary version and the seed. A bug you cannot reproduce cannot be confirmed fixed. If it only happens in production, add logging or a core-dump setting and wait for it to happen again rather than guessing.
- Minimise. Shrink the input while it still fails: halve the replay file, drop symbols, remove config options. A 20-event repro usually makes the cause obvious. Automated shrinking (delta debugging, property-test shrinkers) does this mechanically.
- Localise. Find where the state first goes wrong, not where the program crashes. Bisect in history (which commit?), in the input (which event?) and in the code (assertions or logging at the midpoint of the pipeline).
- Hypothesise and test. State one cause that explains every symptom, predict something new from it, and check. Change one thing at a time.
- Fix, then add the regression test built from the minimised repro, so the bug cannot come back silently.
Bisecting history
If version A worked and version B fails, the first bad commit can be found in about tests among candidate commits. git bisect automates the search, and git bisect run drives it with any script that exits 0 for good and non-zero for bad (exit code 125 means "cannot test this commit, skip it").
git bisect start <bad> <good>
git bisect run ./repro.sh # builds, replays the minimised input, checks the output
git bisect reset
On a toy repository of 16 commits where commit 11 introduced the bug, git bisect run tested commits 8, 12, 10 and 11 (four tests for 15 candidates, ) and printed ... is the first bad commit for "change 11". The same idea applies to inputs: bisect a day of market data by replaying the first half, then the failing half, and so on.
Debugger essentials (gdb and lldb)
A debugger lets you stop a program and read its state. The commands interviewers expect you to know:
| Task | gdb | lldb |
|---|---|---|
| run with arguments | run args | run args |
| breakpoint at function or line | break vwap, break book.cpp:42 | b vwap, b book.cpp:42 |
| conditional breakpoint | break book.cpp:42 if id == 8 | b book.cpp:42 -c 'id == 8' |
| stack trace | bt | bt |
| locals of current frame | info locals | frame variable |
| move between frames | up, down, frame 2 | up, down, frame select 2 |
| step over / into / out | next, step, finish | next, step, finish |
| stop when memory changes | watch pos.qty | watchpoint set variable pos.qty |
| open a core dump | gdb ./bin core | lldb ./bin -c core |
Build with -g for debug information. Optimised builds (-O2) still debug, but variables may be "optimised out" and lines reordered; -O1 -g or -Og -g is a good compromise when chasing a bug. For a production crash, enable core dumps (ulimit -c unlimited on Linux) so the debugger can open the exact state after the fact.
Worked example
reading a crash in lldb
This program crashes on the second lookup. Use the debugger to find out why, and explain the fault address it reports.
#include <cstdio>
#include <map>
struct Order { int id; double px; };
std::map<int, Order*> book;
double price_of(int id) { return book[id]->px; } // operator[] inserts nullptr for an unknown id
int main() {
static Order o{7, 101.25};
book[7] = &o;
std::printf("%.2f\n", price_of(7));
std::printf("%.2f\n", price_of(8));
}
Show solutionHide solution
Build with c++ -std=c++20 -O1 -g crash.cpp -o crash and run it under the debugger in batch mode: lldb --batch -o run -k bt -k "frame variable" ./crash. The relevant part of the real output:
101.25
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x8)
frame #0: 0x0000000100000930 crash`price_of(id=8) at crash.cpp:7:44 [opt] [inlined]
(lldb) bt
* frame #0: 0x0000000100000930 crash`price_of(id=8) at crash.cpp:7:44 [opt] [inlined]
frame #1: 0x000000010000087c crash`main at crash.cpp:13:27 [opt]
(lldb) frame variable
(int) id = 8
Reading it.
- The first call printed
101.25, so the crash is in the second call, withid = 8. address=0x8is the key clue.Orderhas anintat offset 0, 4 bytes of padding, then thedouble pxat offset 8. Readingpxthrough a null pointer reads address . A small fault address almost always means "null pointer plus a field offset".- Why null:
std::map::operator[]default-constructs a missing value, here a nullOrder*, and as a side effect inserts key 8 into the book. Two bugs in one line.
Fix. Look up with find and handle the missing case explicitly (return an optional, or treat it as a protocol error), and add a test that queries an unknown id.
Sanitizers
Many C++ bugs do not crash where they happen; they corrupt memory and fail later, or "work" by luck. Sanitizers are compiler instrumentation that checks every relevant operation at run time and reports the first violation with a stack trace.
| Sanitizer | Flag | Finds | Cost |
|---|---|---|---|
| AddressSanitizer (ASan) | -fsanitize=address | heap, stack and global buffer overflows, use-after-free, double free, use-after-return (opt-in); leaks via LeakSanitizer on Linux | about 2x time, 2–3x memory |
| UndefinedBehaviorSanitizer (UBSan) | -fsanitize=undefined | signed overflow, out-of-bounds array index (when the bound is known), misaligned or null access, invalid shifts, bad casts | small |
| ThreadSanitizer (TSan) | -fsanitize=thread | data races: two threads touch the same memory, at least one writes, no synchronisation | 5–15x time, high memory |
| MemorySanitizer (MSan, clang/Linux) | -fsanitize=memory | reads of uninitialised memory | about 3x |
ASan and UBSan combine (-fsanitize=address,undefined); TSan and MSan must each be a separate build. Add -g -fno-omit-frame-pointer for readable stacks. A common setup is a CI job that runs the whole test suite and the replay tests under ASan+UBSan, and a nightly TSan job for the multithreaded components.
What an ASan report contains. The first line names the error class (heap-buffer-overflow, heap-use-after-free, stack-buffer-overflow, ...) and the faulting address; then the stack of the bad access; then where the memory was allocated (and, for use-after-free, where it was freed); then a line SUMMARY: AddressSanitizer: <error class> <file>:<line> in <function>. Read the first stack for where, the allocation stack for what object.
Why this matters: without instrumentation the bug may be invisible. This program reads one element past the end of a vector:
#include <cstdio>
#include <vector>
int main() {
std::vector<int> sizes = {100, 200, 300};
int* raw = sizes.data();
std::printf("%d\n", raw[3]); // one past the end: heap-buffer-overflow
}
Built normally (-O1 -g) it printed 0 and exited with status 0: a wrong answer and no error. Built with -fsanitize=address on a supported toolchain, ASan stops the program at the read and reports a heap-buffer-overflow, pointing at the 12-byte block the vector allocated for its three ints and saying the access was just past its end.
Worked example
UBSan on an off-by-one and an overflow
A VWAP function and a notional calculation return nonsense without crashing. Build with UBSan and interpret the report.
#include <cstdio>
struct Fill { double px; int qty; };
// Volume-weighted average price of the last n fills (bug: <= instead of <).
double vwap(const Fill (&fills)[4], int n) {
double notional = 0.0;
int volume = 0;
for (int i = 0; i <= n; ++i) {
notional += fills[i].px * fills[i].qty;
volume += fills[i].qty;
}
return notional / volume;
}
int notional_cents(int px_cents, int qty) { return px_cents * qty; }
int main() {
Fill fills[4] = {{100.0, 10}, {100.5, 20}, {101.0, 30}, {99.5, 40}};
std::printf("vwap = %.4f\n", vwap(fills, 4));
std::printf("notional = %d\n", notional_cents(250'000, 10'000));
}
Show solutionHide solution
Build and run with c++ -std=c++20 -O1 -g -fsanitize=undefined ubsan.cpp -o ubsan && ./ubsan. Real output:
ubsan.cpp:10:21: runtime error: index 4 out of bounds for type 'const Fill[4]'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ubsan.cpp:10:21
ubsan.cpp:10:35: runtime error: index 4 out of bounds for type 'const Fill[4]'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ubsan.cpp:10:35
ubsan.cpp:11:19: runtime error: index 4 out of bounds for type 'const Fill[4]'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ubsan.cpp:11:19
ubsan.cpp:16:61: runtime error: signed integer overflow: 250000 * 10000 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ubsan.cpp:16:61
vwap = 0.0000
notional = -1794967296
Interpretation.
- Off-by-one. The loop reads
fills[4], one past a 4-element array, at every use in lines 10 and 11. Once undefined behaviour occurs the compiler owes you nothing: here the printed VWAP is0.0000, while the correct value is . Fix:i < n. - Overflow. , which exceeds
INT_MAX. The printed value is , but because signed overflow is undefined the optimiser may produce anything. Fix: usestd::int64_tfor notionals and quantities.
Both bugs produce plausible-looking garbage rather than a crash, which is exactly why the test suite should run under sanitizers.
Knowledge check
A regression appeared somewhere in the last 1,000 commits and you have a scripted test that detects it. About how many test runs does git bisect need in the worst case?
Knowledge check
A multithreaded position tracker occasionally reports totals that are slightly too small, with no crash. Which tool is designed to find the likely cause?
Knowledge check
A process crashes with a segmentation fault at address 0x18. What is the most likely immediate cause?
Key takeaways
- Reproduce, minimise, localise, hypothesise, fix, and add the regression test, in that order.
git bisect runfinds the first bad commit in about automated tests; bisect inputs the same way.- Know the core debugger commands: breakpoints (conditional),
bt, frame variables, stepping, watchpoints and opening a core dump. - A fault at a small address means null pointer plus field offset.
- Run tests under ASan+UBSan routinely and TSan for concurrent code; memory bugs and undefined behaviour often give plausible wrong answers rather than crashes.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).