Diagnostics, debugging, and evidence
Build a reproducible case, investigate with the right tools, understand detector limits, and turn repairs into contract-focused checks.
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
#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 -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 build | Useful evidence and limit |
|---|---|
| AddressSanitizer | Many invalid bounds/lifetime accesses; not every error and not a general uninitialized-value detector. |
| UndefinedBehaviorSanitizer | Selected UB checks such as signed overflow and alignment; coverage is incomplete. |
| ThreadSanitizer | Dynamic evidence about races on exercised executions; not proof of all schedules or algorithm correctness. |
| Memory analysis | Tools can differ in uninitialized-value and leak coverage; host support matters. |
| Static analysis | Examines 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
#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
- WG14 N1570 — public C11 committee draft: 5.1.1.3, 7.2. Stable core rules used for the C17 baseline; not the final ISO publication.
- GCC: warning options
- GCC: instrumentation options
- GDB: breakpoints and watchpoints
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.
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.
Read the explanation for every choice
- 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.
- Every possible execution is valid C.
A finite test run does not explore every possible execution.
- 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.-Walldoes not mean every possible warning, and-Wall -Wextradoes not enable all conversion warnings.-Werrortreats 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
gdblet 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-tidyandcppcheckexamine 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.