
Recall first from Sanitizers: ASan and UBSan
- AddressSanitizer catches out-of-bounds and use-after-free at about 2x slowdown; UBSan catches signed overflow and friends.
- ASan works through shadow memory, redzones and a quarantine of freed blocks; uninitialised reads are MemorySanitizer's or Valgrind's job.
- A sanitizer stops the program the moment a rule is broken and reports the exact source line, so you find the bug by running the program rather than by reasoning about it.
Valgrind memcheck versus ASan, and diagnosing the mistakes they catch
4 min readSanitizers need a rebuilt, instrumented binary and they miss uninitialised reads. This lesson answers how Valgrind finds those without a rebuild, and how the compiler itself exploits undefined behaviour to remove your checks.
ASan requires you to rebuild the program with instrumentation. Valgrind memcheck takes the opposite approach: it runs your existing binary, compiled with -g for line numbers, inside a dynamic translation layer that validates every load, store and system call against a shadow model of addressability and definedness. No recompilation is needed, which makes it the tool of choice when you cannot rebuild, or when the bug is in a library you did not compile.
gcc -g -o prog prog.c # ordinary build, no sanitizer
valgrind --leak-check=full --track-origins=yes ./prog
Typical leak summary (yours will differ):
==12345== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12345== at 0x...: malloc (vg_replace_malloc.c:...)
==12345== by 0x...: main (prog.c:7)
==12345== LEAK SUMMARY:
==12345== definitely lost: 40 bytes in 1 blocks
A heap memory that was allocated and is never freed, so the pointer to it is lost and the bytes stay allocated until the process exits is reported at exit by --leak-check=full, which distinguishes "definitely lost" from "still reachable". --track-origins=yes makes memcheck report where an uninitialised value came from, not just where it was used.
The tradeoff is cost. Valgrind typically slows a program by a factor of 10 to 50, because it is emulating rather than instrumenting, while ASan's overhead is about 2x. Valgrind also needs explicit architecture support: it runs on x86, amd64, ARM and AArch64 among others, but some small embedded targets are unsupported, and it needs enough RAM for its own bookkeeping. The division of labour is: use ASan in CI for speed and for stack and global overruns, and reach for Valgrind when you cannot rebuild, need leak details, or suspect an uninitialised read. Do not run an ASan-instrumented binary under Valgrind; the two do not cooperate.
Common mistakes, and how to diagnose them
Three mistakes account for most of the time spent in this territory. Each follows the same shape: a symptom, the underlying cause, the tool that diagnoses it, and the fix.
The program works at -O0 and misbehaves at -O2. Symptom: a program that passes all tests in a debug build produces wrong results or crashes when optimised. Cause: usually undefined behaviour such as signed overflow or a null dereference before a null check, which the optimiser is allowed to exploit. Diagnosis: rebuild with -fsanitize=undefined,address and run; UBSan names the overflowing line. Fix: remove the UB, then keep the sanitizer in CI so it cannot return.
Garbage after a string, or a crash in a function that only reads. Symptom: printf("%s", dst) prints the string plus junk, or strlen runs off the end. Cause: strncpy or memcpy filled dst without a terminator. Diagnosis: ASan reports a heap-buffer-overflow or stack-buffer-overflow in the reading function, pointing back to the unterminated buffer. Fix: use snprintf or write the terminator explicitly.
Abort in the allocator, or a crash far from the bug. Symptom: free(): double free detected in tcache 2, or a crash in unrelated code. Cause: two owners freeing the same pointer, or use-after-free where freed memory was recycled. Diagnosis: ASan reports the double free or heap-use-after-free with a stack trace to the first free; Valgrind shows invalid reads and writes. Fix: write down who owns each allocation, free it exactly once, and set the pointer to NULL after freeing so a second free is a harmless no-op.
When the compiler exploits UB, and how to reason about correctness
6 min readThe most unsettling fact in this lesson is not that UB is dangerous, but that the compiler actively relies on it. Two examples show the mechanism.
The first is the deleted null check.
int deref_then_check(int *p) {
int x = *p; /* if p were NULL, this dereference is UB */
if (p == NULL) /* the compiler may remove this test */
return 0;
return x;
}
The dereference *p would be undefined if p were null. A valid program can never reach UB, so the compiler concludes that p is non-null at the dereference, and therefore at the test after it. The if (p == NULL) branch is dead code and is removed. A caller that passes NULL no longer gets the safe return 0; it gets a null dereference, and the "defensive" check it wrote has vanished.
The second is signed overflow in a loop bound.
int always_true(int x) {
return x + 1 > x; /* assumed true, because overflow is UB */
}
If x + 1 could overflow, the comparison might be false for INT_MAX. But overflow is undefined, so the compiler assumes it cannot happen, and x + 1 > x is always true. The function compiles to "return 1", and a loop written as for (i = 0; i < n; i++) can be optimised on the same assumption that i never wraps.
Dereference: the program reads through
pat the top of the function.Assume: because a null dereference would be undefined, the compiler assumes
pis non-null at that point.Propagate: the assumption holds for the rest of the function, including the later test.
Delete: the
p == NULLtest is always false, so the branch is removed.Consequence: a null call no longer returns safely; it dereferences null and crashes.
You can change the contract with flags. -fwrapv tells gcc and clang to define signed integer overflow as wrapping, two's-complement style, which removes the overflow assumption. -fno-strict-overflow disables the optimisations that rely on the absence of overflow, without fully defining the behaviour. Neither makes the code portable; both only change what one compiler does. The correct response is to remove the UB, and to keep -fsanitize=undefined on so a new occurrence is caught at run time.
This brings the reasoning full circle to the the idealised execution model the C standard uses to define behaviour, which a conforming implementation must reproduce for every defined program. The standard defines what a program does by describing an abstract machine with its own memory and evaluation rules. A conforming compiler must produce a real program whose observable behaviour, its I/O and its volatile accesses, matches the abstract machine. Anything the standard does not define gives the compiler no such obligation, and it is free to assume the undefined thing never happens.
That obligation also rests on a notion of evaluation order. A a point in the evaluation of an expression at which all side effects of previous evaluations are complete and no side effects of the following evaluations have begun is what separates "before" from "after" in C. Modifying the same object twice, or reading it and modifying it, between two sequence points is undefined, which is why i = i++ and a[i] = i++ are invalid. C11 rephrased the idea as "sequenced before" and "sequenced after", but the rule is the same: do not write to the same object twice without a sequence point between.
Going deeperWhy i = i++ is undefined
The assignment i = i++ writes to i twice, once for the increment and once for the assignment, with no sequence point ordering the two. The standard therefore imposes no requirements on the result or on the program. Even where a compiler produces a consistent answer, another compiler, or the same compiler at a different optimisation level, may produce another, because the program is not defined. The fix is to write i = i + 1; or i++; alone, so each object is modified once per statement.
The closing rule of the testing mindset follows directly: passing tests does not prove the absence of UB. A test only proves that, on one compiler, one optimisation level and one machine, the observable behaviour matched. UB can be latent, manifesting only when the optimiser or the hardware changes. The reliable practice is to build a small harness with expected output, compare programmatically, and run the whole thing under sanitizers as a make target.
CFLAGS = -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Wstrict-prototypes -Werror -g -O1 -fsanitize=address,undefined
check: prog
./prog test_input.txt | diff expected_output.txt -
The harness runs the instrumented program, and diff fails the target on any deviation, so a regression or a sanitizer report fails the build automatically. Tests establish that the code does what you intended; sanitizers establish that it is defined at all. You need both.
learner@embeddex:~/lab$ # build without optimisation learner@embeddex:~/lab$ gcc -O0 -o ub0 ub.c learner@embeddex:~/lab$ # at -O0 the addition really wraps, so INT_MAX + 1 is not greater learner@embeddex:~/lab$ ./ub0 2147483647 1 learner@embeddex:~/lab$ # the same source, now optimised learner@embeddex:~/lab$ gcc -O2 -o ub2 ub.c learner@embeddex:~/lab$ # at -O2 the compiler assumes overflow cannot happen, so the test is alw ays true learner@embeddex:~/lab$ ./ub2 2147483647 1
Try it
1 min readOpen your lab environment and build a single program that contains one deliberate bug of each kind: a signed overflow, an out-of-bounds write, a use-after-free and a double free. Compile it once with -fsanitize=address,undefined, run it, and map each report back to the exact line; then build the same file without sanitizers and run it under Valgrind with --leak-check=full --track-origins=yes, and compare which tool reports which bug. Next take the small utility you wrote in an earlier session and drive it to zero warnings under -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Wstrict-prototypes -Werror. Finally add assert for its internal invariants and return-code checks for its external input, write a test harness that feeds it a known input and compares the output with diff, and wire that harness into a make check target that runs the sanitizer build. These are the exact skills the next lesson's ringlog project and the M2 readiness test build on.
Key takeaways
- Valgrind needs no rebuild and catches uninitialised reads and leaks, at 10 to 50x the cost.
- A program that passes its tests can still contain UB; run sanitizers in CI, because tests only prove what they exercise.
- Because a valid program can never execute undefined behaviour, the compiler removes code that only makes sense if it did, such as a null check after a dereference; -fwrapv changes one compiler's contract, but the fix is to remove the UB.
Reflect
- Explain to a colleague, in two sentences: compare ASan and Valgrind memcheck, then apply defensive practices: check return codes, bound-check writes, validate input and prefer snprintf over strcpy.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.