Debug memory and input bugs in C

8 steps · about 4 h 10 min · Intermediate

  1. Turn on useful compiler warnings (reference, GCC documentation, 30 min)

    Expose suspicious conversions, declarations and control flow before running the program.

  2. Build with sanitizers (reference, GCC documentation, 30 min)

    Instrument the executable so invalid memory and undefined behaviour fail near their source.

  3. Inspect a failing execution (guide, GDB documentation, 40 min)

    Use breakpoints, backtraces and variable inspection to connect a crash to program state.

  4. Check array bounds (reference, cppreference, 30 min)

    Reason about element counts, indices and array-to-pointer conversion at each access.

  5. Trace object lifetimes (reference, cppreference, 30 min)

    Avoid returning addresses of expired objects or using storage after its lifetime ends.

  6. Pair allocation with validation (reference, cppreference, 30 min)

    Check allocation results and calculate requested sizes without overflow.

  7. Read bounded input (reference, cppreference, 25 min)

    Replace unbounded or ambiguous input handling with a size-aware line read.

  8. Verify every cleanup path (reference, cppreference, 35 min)

    Release each owned allocation exactly once on success and failure paths, then rerun the sanitizers.