YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Correctness & careChapter 66 of 73

Diagnostics, debugging, and evidence

Build a reproducible case, investigate with the right tools, understand detector limits, and turn repairs into contract-focused checks.

5 min readIntermediateC17 baseline
Offline reading
In this chapter8 sections

Debugging begins with a mismatch between expected and observed behavior. A useful investigation makes the failure repeatable, forms a specific explanation, and checks the evidence. Tools help, but each tool sees only part of the problem.

1. Make the observation reproducible

Record input, compiler/version, flags, target, relevant library versions, and expected versus observed output. Reduce the case while keeping the failure. Removing a call, changing a type, or disabling optimization can change lifetimes, ordering, or the very UB you are investigating. A smaller program that no longer reproduces the issue is useful comparison evidence, not automatically proof of a repair.

2. Begin with a checked, inspectable build

Complete C17 program · diagnose.c
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const int values[] = { 2, 4, 6 };
    size_t count = sizeof values / sizeof values[0];
    int sum = 0;
    for (size_t i = 0; i < count; ++i) sum += values[i];
    assert(sum == 12);
    if (printf("sum=%d\n", sum) < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
GCC / GNU tools · example commands
gcc -std=c17 -Wall -Wextra -Wpedantic -Wconversion -Wformat=2 -g -O0 diagnose.c -o diagnose
./diagnose

Save the complete source as diagnose.c and run these example GCC commands in a suitable Unix-like environment. -g emits debug information; -O0 is useful for an initial source-oriented inspection. This does not promise identical debugger behavior on every target. Also reproduce the actual production optimization/configuration when investigating a configuration-sensitive problem.

Warnings expose suspicious conversions, formats, declarations, or control flow. -Wall is a named warning set, not every possible warning; -Wextra and -Wconversion add other checks. -Werror is a build policy for enabled diagnostics, not a proof that a successful program is correct. Investigate a warning’s cause before suppressing it, and document a justified narrow exception.

3. Inspect a hypothesis with a debugger

A breakpoint stops at a selected location or condition; a watchpoint can stop when a relevant expression changes. Inspect indices, lengths, object lifetime, and the path taken before the symptom. A debugger’s variable display is evidence about that build, not a new language guarantee. Optimized code can reorder or remove operations and report variables as unavailable. Logging can also perturb scheduling and timing.

4. Match a detector to the question

Tool or buildUseful evidence and limit
AddressSanitizerMany invalid bounds/lifetime accesses; not every error and not a general uninitialized-value detector.
UndefinedBehaviorSanitizerSelected UB checks such as signed overflow and alignment; coverage is incomplete.
ThreadSanitizerDynamic evidence about races on exercised executions; not proof of all schedules or algorithm correctness.
Memory analysisTools can differ in uninitialized-value and leak coverage; host support matters.
Static analysisExamines paths without running them; both false positives and missed defects are possible.

With a supporting GCC target, -fsanitize=address,undefined selects the first two instrumentations; debug information and a frame-pointer-preserving build can improve reports. A separate -fsanitize=thread build asks a different question. GCC does not allow ThreadSanitizer to be combined with AddressSanitizer or LeakSanitizer. Runtime availability is independent of whether the compiler accepts the flag. A report’s first invalid operation is often more useful than the last crash.

5. Turn a repair into a boundary-focused regression check

Complete C17 program
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>

static bool last_value(const int *values, size_t count, int *result)
{
    if (values == NULL || result == NULL || count == 0) return false;
    *result = values[count - 1];
    return true;
}

int main(void)
{
    int values[] = { 2, 4, 6 };
    int result = 99;
    bool empty = last_value(values, 0, &result);
    assert(!empty && result == 99);
    bool one = last_value(values, 1, &result);
    assert(one && result == 2);
    bool many = last_value(values, 3, &result);
    assert(many && result == 6);
    return 0;
}

The helper rejects zero count before subtracting one. The checks preserve the rejected result and cover empty, one-element, and multiple-element cases. Its caller must still provide count readable elements. Test the contract boundary that explains the failure, not a string matching the implementation. A passing suite narrows uncertainty; reviews and precondition reasoning still matter.

Primary references and further reading

Before you move on

  • A useful bug report makes a failure reproducible and states the expected behavior.
  • Diagnostics, debugger observations, and sanitizers answer different questions.
  • A regression check should exercise the boundary or assumption that caused the failure.
Keep these ideas separate
No report / Proof of correctness
A tool’s silence is limited by its coverage, instrumentation, inputs, and the properties it can detect.
Explain it in your own words

What evidence would let someone else investigate your failure without guessing your compiler options or input?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

What does a clean sanitizer run establish?
Read the explanation for every choice
  1. No covered problem was reported in the executions exercised.

    ✓ Correct reasoning. This is useful evidence, but it is not proof for every input, path, or tool limitation.

  2. Every possible execution is valid C.

    A finite test run does not explore every possible execution.

  3. The implementation no longer needs language rules.

    Tools complement the language rules; they do not replace them.

General

Quick reference from the earlier edition

Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.

Because so many C errors are defined by the standard only as "undefined behavior" rather than caught at compile time, tooling plays an outsized role in writing reliable C:

  • Compiler warnings. A useful GCC/Clang starting point is -std=c17 -Wall -Wextra -Wpedantic -Wconversion -Wformat=2. -Wall does not mean every possible warning, and -Wall -Wextra does not enable all conversion warnings. -Werror treats enabled warnings as errors when that policy is appropriate. Diagnostics can find many mistakes but do not prove that a program has no undefined behavior.
  • assert. Cheap, built-in runtime checks for conditions that should always hold (Section 26).
  • Debuggers. Tools like gdb let a programmer set breakpoints, step through execution line by line, and inspect variables and memory — indispensable for pinning down a crash's exact cause.
  • Memory and runtime tools. Valgrind Memcheck can report invalid memory accesses, some uninitialized-value uses, and leaks. AddressSanitizer (-fsanitize=address) detects many bounds/lifetime errors; UndefinedBehaviorSanitizer (-fsanitize=undefined) detects selected forms of undefined behavior such as signed overflow. Their coverage differs; neither catches every error, and ordinary AddressSanitizer is not a general uninitialized-memory detector. Tool availability and leak detection depend on the platform.
  • Static analysis. Tools such as clang-tidy and cppcheck examine source code without running it, catching whole classes of bugs — and, in stricter industrial settings, standards-conformance issues — before the program is ever executed.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 66 / 73

In this chapter

Diagnostics, debugging, and evidence

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping