Skip to content
LeetQuant
QD09 Testing, Profiling and Debugging

QD09 · Testing, Profiling and Debugging · Lesson 2 of 5

Debugging

Debug methodically: reproduce, minimise, bisect, then inspect with a debugger and catch memory and undefined-behaviour bugs with sanitizers.

17 min

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

  1. 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.
  2. 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.
  3. 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).
  4. Hypothesise and test. State one cause that explains every symptom, predict something new from it, and check. Change one thing at a time.
  5. 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 log⁡2n\log_2 n tests among nn 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, ⌈log⁡215⌉=4\lceil \log_2 15 \rceil = 4) 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:

Taskgdblldb
run with argumentsrun argsrun args
breakpoint at function or linebreak vwap, break book.cpp:42b vwap, b book.cpp:42
conditional breakpointbreak book.cpp:42 if id == 8b book.cpp:42 -c 'id == 8'
stack tracebtbt
locals of current frameinfo localsframe variable
move between framesup, down, frame 2up, down, frame select 2
step over / into / outnext, step, finishnext, step, finish
stop when memory changeswatch pos.qtywatchpoint set variable pos.qty
open a core dumpgdb ./bin corelldb ./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 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, with id = 8.
  • address=0x8 is the key clue. Order has an int at offset 0, 4 bytes of padding, then the double px at offset 8. Reading px through a null pointer reads address 0+80 + 8. 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 null Order*, 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.

SanitizerFlagFindsCost
AddressSanitizer (ASan)-fsanitize=addressheap, stack and global buffer overflows, use-after-free, double free, use-after-return (opt-in); leaks via LeakSanitizer on Linuxabout 2x time, 2–3x memory
UndefinedBehaviorSanitizer (UBSan)-fsanitize=undefinedsigned overflow, out-of-bounds array index (when the bound is known), misaligned or null access, invalid shifts, bad castssmall
ThreadSanitizer (TSan)-fsanitize=threaddata races: two threads touch the same memory, at least one writes, no synchronisation5–15x time, high memory
MemorySanitizer (MSan, clang/Linux)-fsanitize=memoryreads of uninitialised memoryabout 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 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 is 0.0000, while the correct value is 100⋅10+100.5⋅20+101⋅30+99.5⋅40100=100.20\frac{100 \cdot 10 + 100.5 \cdot 20 + 101 \cdot 30 + 99.5 \cdot 40}{100} = 100.20. Fix: i < n.
  • Overflow. 250,000×10,000=2.5×109250{,}000 \times 10{,}000 = 2.5 \times 10^{9}, which exceeds INT_MAX =231−1≈2.147×109= 2^{31} - 1 \approx 2.147 \times 10^{9}. The printed value is 2.5×109−232=−1,794,967,2962.5 \times 10^{9} - 2^{32} = -1{,}794{,}967{,}296, but because signed overflow is undefined the optimiser may produce anything. Fix: use std::int64_t for 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 run finds the first bad commit in about log⁡2n\log_2 n 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).