How a debugging round runs
You are given 20–60 lines of code and told "this gives wrong results in production" or simply "what is wrong with this?". The interviewer is grading your method as much as the find:
- Read for intent first. Say in one sentence what the code is supposed to do.
- Form a hypothesis from the symptom. Wrong totals that grow over time suggest shared state; results that depend on the run suggest a race or uninitialised memory; "works in debug, fails in release" suggests undefined behaviour.
- Reproduce with the smallest input that shows it, and predict the output before running.
- Name the tool you would use: an assertion, a print of identities (
id(), addresses), AddressSanitizer (-fsanitize=address) for memory errors, ThreadSanitizer (-fsanitize=thread) for races, a debugger watchpoint. - Fix the cause, not the symptom, and say what test would have caught it.
Try each exercise for three to five minutes before reading the solution. All four were run; outputs are real.
Worked example
Exercise 1 (Python): fills leaking between days
A helper collects fills. On day two the report contains day one's fills too. Find the bug.
def add_fill(symbol, qty, fills=[]):
fills.append((symbol, qty))
return fills
day1 = add_fill("AAPL", 100)
day2 = add_fill("MSFT", 50)
print(day1)
print(day2, day1 is day2)
print(add_fill.__defaults__)
Show solutionHide solution
Output:
[('AAPL', 100), ('MSFT', 50)]
[('AAPL', 100), ('MSFT', 50)] True
([('AAPL', 100), ('MSFT', 50)],)
Bug. Default arguments are evaluated once, when def runs. Every call without fills shares the same list, so state leaks between calls. day1 is day2 being True is the proof, and __defaults__ shows the accumulated list living on the function object.
How to find it. The symptom "totals grow across calls that should be independent" points to shared mutable state. Check identities (is, id()) of the returned objects. Linters flag it (Ruff and Pylint both have a mutable-default rule).
Fix.
def add_fill_fixed(symbol, qty, fills=None):
if fills is None:
fills = []
fills.append((symbol, qty))
return fills
print(add_fill_fixed("AAPL", 100), add_fill_fixed("MSFT", 50))
[('AAPL', 100)] [('MSFT', 50)]
The same trap exists for dict and set defaults and for dataclass fields (which is why dataclasses forces field(default_factory=list)).
Worked example
Exercise 2 (Python): one price level becomes two
A book aggregates quantity by price. An order entered at 100.3 and another entered "two ticks above 100.1" should land on the same level. The book shows two levels. Why?
TICK = 0.1
book = {}
def add(price, qty):
book[price] = book.get(price, 0) + qty
def ticks_above(price, n):
for _ in range(n):
price += TICK
return price
add(100.3, 5) # order entered directly at 100.3
add(ticks_above(100.1, 2), 7) # "two ticks above 100.1"
print(book)
print(len(book), "levels")
Show solutionHide solution
Output:
{100.3: 5, 100.29999999999998: 7}
2 levels
Bug. 0.1 has no exact binary representation, so repeated addition accumulates rounding error, and 100.1 + 0.1 + 0.1 is a different float from the literal 100.3. Floats used as dict keys (or compared with ==) split what should be one level.
How to find it. "Two keys that look the same" means the keys are not equal: print repr of each key, or key1 == key2. Any code that uses prices as keys, in sets, or in equality tests is a suspect.
Fix. Represent prices as integer ticks at the boundary (on parsing) and only convert to decimal for display:
def to_ticks(price):
return round(price / TICK)
fixed = {}
for p, q in [(100.3, 5), (ticks_above(100.1, 2), 7)]:
t = to_ticks(p)
fixed[t] = fixed.get(t, 0) + q
print(fixed)
{1003: 12}
Rounding after the error has accumulated works here, but the robust design is to never hold prices as floats in the book at all: parse them straight to ticks (or use fixed-point integers with a known scale, as most feeds already do on the wire).
Worked example
Exercise 3 (C++): a partial fill that disappears
The code records a partial fill of 4 on the first order. It prints a quantity of 10 instead of 6, and in another build it crashes. Find the bug.
#include <cstdio>
#include <vector>
struct Order { int id; double px; int qty; };
int main() {
std::vector<Order> orders;
orders.push_back({1, 100.5, 10});
Order& first = orders.front(); // reference into the vector's buffer
const void* before = orders.data();
for (int i = 2; i <= 5; ++i)
orders.push_back({i, 100.5 + i, 10}); // may reallocate
first.qty -= 4; // partial fill, written through first
std::printf("buffer moved: %s\n", before != orders.data() ? "yes" : "no");
std::printf("order 1 qty = %d (expected 6)\n", orders.front().qty);
}
Show solutionHide solution
Output (-O2 -Wall, no warnings):
buffer moved: yes
order 1 qty = 10 (expected 6)
Bug. push_back reallocated when size exceeded capacity, moving the elements to a new buffer and freeing the old one. first still refers into the freed buffer, so first.qty -= 4 is a use after free: undefined behaviour. Here it quietly wrote to dead memory and the update was lost; with a different allocator state it could corrupt another object or crash, which matches "different builds behave differently".
How to find it. "An update that vanishes" plus "a reference or pointer into a container that is later modified" is the pattern. Print data() before and after, as above. AddressSanitizer (-fsanitize=address) reports this class of bug as a heap-use-after-free at the exact line, with the stack of the push_back that freed the memory; it is the first tool to name.
Fix. Hold an index (or an id looked up in a map), not a reference, across operations that can reallocate; or reserve the full size first if it is known; or use a container with stable addresses (std::deque for push at the ends, std::list, or a pool with stable slots).
#include <cstdio>
#include <vector>
struct Order { int id; double px; int qty; };
int main() {
std::vector<Order> orders;
orders.push_back({1, 100.5, 10});
std::size_t first = 0; // keep an index, not a reference
for (int i = 2; i <= 5; ++i)
orders.push_back({i, 100.5 + i, 10});
orders[first].qty -= 4;
std::printf("order 1 qty = %d (expected 6)\n", orders.front().qty);
}
order 1 qty = 6 (expected 6)
Worked example
Exercise 4 (C++): fill counts that change run to run
Four threads each process a million fills and increment a shared counter. The total should be 4,000,000. Find the bug, and explain why it "goes away" in the optimised build.
#include <cstdio>
#include <thread>
#include <vector>
long fills = 0; // shared, unsynchronised
void on_fills(int n) { for (int i = 0; i < n; ++i) ++fills; }
int main() {
std::vector<std::thread> ts;
for (int t = 0; t < 4; ++t) ts.emplace_back(on_fills, 1'000'000);
for (auto& t : ts) t.join();
std::printf("fills = %ld (expected 4000000)\n", fills);
}
Show solutionHide solution
Three runs at -O0, then three at -O2:
fills = 1604657 (expected 4000000)
fills = 1435502 (expected 4000000)
fills = 1773736 (expected 4000000)
fills = 2000000 (expected 4000000)
fills = 4000000 (expected 4000000)
fills = 4000000 (expected 4000000)
Bug. ++fills is a load, an add and a store. Two threads can load the same value and both store value + 1, losing an increment. Unsynchronised concurrent writes are a data race, which is undefined behaviour in C++.
Why -O2 hides it. Because a race is UB, the compiler may assume no other thread touches fills during the loop and turn it into a single fills += n. The window for a lost update shrinks to one read-modify-write per thread, so most runs look right and one run lost an entire thread's million. A bug that appears only sometimes and only in some builds is exactly what races look like; "it passes at -O2" proves nothing.
How to find it. Non-deterministic totals point to shared mutable state across threads: list every variable written by more than one thread. ThreadSanitizer (-fsanitize=thread) reports the racing accesses with both stacks.
Fix. Make the counter atomic (relaxed ordering is enough, because the value does not publish other data), or better, accumulate locally per thread and combine once, which also avoids cache-line contention:
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
std::atomic<long> fills{0};
void on_fills(int n) { for (int i = 0; i < n; ++i) fills.fetch_add(1, std::memory_order_relaxed); }
int main() {
std::vector<std::thread> ts;
for (int t = 0; t < 4; ++t) ts.emplace_back(on_fills, 1'000'000);
for (auto& t : ts) t.join();
std::printf("fills = %ld (expected 4000000)\n", fills.load());
}
fills = 4000000 (expected 4000000)
(Run twice at -O0, the build that exposed the race, with the same result both times.)
Knowledge check
A C++ service gives correct results in a debug build but wrong, varying results in the release build. Which cause is most likely?
Knowledge check
In Exercise 3, which change does NOT fix the dangling reference in general?
Knowledge check
Why did printing a single float (print(ticks_above(100.1, 2))) look harmless while printing the dict revealed the bug?
Key takeaways
- Map the symptom to a bug class: growing shared totals (mutable state), "same but different" keys (float equality), vanished writes or crashes (dangling references), run-to-run variation (races).
- Reproduce with the smallest input and predict the output before running.
- Name the tool: identity checks in Python, AddressSanitizer for memory errors, ThreadSanitizer for races, assertions on invariants.
- Never use floats as price keys; parse prices to integer ticks at the boundary.
- Never hold references or pointers into a
vectoracross operations that can reallocate. - Passing at
-O2does not prove a race-free program; UB can hide as easily as it appears.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).