Saltar al contenido ForoHackers

AddressSanitizer: what it catches that your tests do not

FuzzingGestión de memoriaProgramación segura
#1004 · heap_spray_and_pray · · Denunciar

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.

#1400 · git_blame_myself · · Denunciar

I added an ASan job to our CI after reading something like this. First run: three bugs in code that had been "stable" for years. Humbling and very worth it.

#1401 · null_terminated_hopes · · Denunciar

Note that the program above "works" precisely because malloc rounds up. If you want to feel despair, run it through a different allocator and watch it behave differently. Undefined means undefined, not "it worked last time".

#1402 · rubber_duck_supervisor · · Denunciar

What does it not catch? I would like to know the limits before I trust the green tick.

#1403 · heap_spray_and_pray · · Denunciar

Good question. It only sees code that ran, so coverage matters. It misses reads of uninitialised memory (that is MemorySanitizer's job), data races (ThreadSanitizer) and logic errors. And an overflow that stays inside a larger valid object, like one field spilling into the next in the same struct, may not trip a redzone. Sanitizers narrow the net, they do not close it.

Inicia sesión o únete para responder.