Debug C memory errors with sanitizers

8 steps · about 4 h 5 min · Intermediate

  1. Enable useful compiler warnings (reference, AddressSanitizer documentation, 30 min)

    Catch suspicious conversions, declarations and control flow before runtime investigation.

  2. Classify memory-safety failures (guide, Wikipedia, 30 min)

    Distinguish bounds, lifetime, initialization and ownership errors to guide the search.

  3. Build with AddressSanitizer (reference, Clang documentation, 35 min)

    Instrument memory accesses and obtain a precise report near the first invalid operation.

  4. Check undefined behaviour (reference, Clang documentation, 30 min)

    Expose invalid arithmetic, alignment and type operations that may otherwise appear intermittent.

  5. Read the failing call stack (guide, Wikipedia, 25 min)

    Trace the bad operation back through callers and distinguish symptom from origin.

  6. Reduce the failing input (guide, Wikipedia, 30 min)

    Remove unrelated paths until the ownership or boundary mistake is visible and repeatable.

  7. Make ownership explicit (guide, Wikipedia, 30 min)

    Document who allocates, transfers and releases each resource even though C lacks automatic ownership.

  8. Keep a sanitizer regression test (reference, CMake documentation, 35 min)

    Automate the smallest failing scenario so the corrected boundary remains protected.