liveBook · Manning

Undefined behavior

As explained in Modern C, Third Edition

Undefined behavior is a C execution condition for which the standard imposes no requirements on the program's subsequent behavior.

A loop that can reach an undefined state

Consider two loops that increment a counter while it is nonzero. The counter’s type matters: the signed version can reach an increment for which signed arithmetic is undefined. It is not safe to reason that it will simply wrap around like an unsigned counter. section 5.7.5

for (unsigned i = 1; i; ++i) do_something();
for (  signed i = 1; i; ++i) do_something();

Compare the counter types before predicting whether either loop reaches the statement after it. section 5.7.5

Undefined behavior means that an operation has taken execution outside the guarantees of C’s abstract state machine. Once that happens, no assumption about the continuation is justified. A compiler may choose an outcome for the operation or reason that the undefined state is never reached. Apparently normal output is therefore no proof of safety: a change of platform, compiler, or options may expose the failure. section 5.7.5

A format mismatch

A printf call also depends on a validity condition: its format specifier and modifier must suit the corresponding argument. The function uses the format to interpret its arguments; an inappropriate format makes the behavior undefined. Treat compiler warnings about format mismatches as defects to fix. section 8.4.4

TAKEAWAY: Prevent the operation that causes undefined behavior; do not rely on how failure happens to appear. Program failure may be silent or conspicuous, and its visible effects need not reveal its cause. section 5.7.5 section 15.0

How Modern C, Third Edition covers it

How deep it goes
Explains compiler assumptions and unreliable outcomes through signed arithmetic, while deferring a fuller treatment of program failure.
Examples
Compares signed and unsigned increment loops and examines mismatched printf format specifiers.
What it assumes
Assumes familiarity with C loops, integer types, and function arguments; introduces the consequences of an undefined state.
What you can do after
Diagnose/debug with it by identifying invalid operations rather than trusting apparently normal output.
How it connects
Connects undefined behavior to signed integer arithmetic, formatted output, compiler optimization, and program failure.

Also explained in

Compare how 7 books explain undefined behavior →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.