Here is a tiny C program with a bug that works fine on most runs:
#include <stdlib.h>
#include <string.h>
int main(void) {
char *p = malloc(8);
strcpy(p, "123456789"); /* needs 10 bytes: 9 chars + NUL */
free(p);
return 0;
}
Compiled normally, this runs without complaint. The two extra bytes land in padding the allocator gave you for free, so nothing visibly breaks. It is a time bomb, not a working program.
Compile it in a lab with -fsanitize=address -g -O1 and it stops at the exact line: heap-buffer-overflow, with the allocation stack trace and the offset past the end.
How it works, briefly:
- Shadow memory: one shadow byte describes 8 bytes of application memory and says how many of them are valid to touch.
- Redzones: every allocation gets poisoned padding before and after, so an out-of-range access hits a poisoned byte.
- Instrumentation: the compiler checks the shadow before each load and store.
- Quarantine: freed memory is not reused straight away, and stays poisoned, which is what exposes use-after-free.
The cost is roughly 2x slowdown and more memory, so it belongs in tests and fuzzing builds, not in production. Pair it with a fuzzer and you find the bug in minutes instead of waiting for a customer's weird input.
Defensive takeaway: if your CI does not have one sanitizer job, it is missing the cheapest bug detector there is.