Behavior, guarantees, and undefined behavior
Separate undefined, unspecified, and documented implementation choices, then justify the preconditions before an operation.
In this chapter9 sections
A result from one run does not always tell us what C guarantees. Some choices are documented by the implementation, some are left unspecified, and some operations have undefined behavior. These categories tell us which conclusions are justified.
Need the ideas side by side? Open the concept guide.
1. Separate three kinds of freedom
| Category | Meaning |
|---|---|
| Unspecified behavior | Several permitted choices; the implementation need not document which it chooses. Example: order of independent function arguments. |
| Implementation-defined behavior | A permitted implementation choice that must be documented. Example: plain char signedness or right shift of a negative signed value. |
| Undefined behavior | The standard imposes no requirements for that execution. A crash, rejection, warning, or consistent result is not promised. |
Unspecified does not mean “anything can happen.” Each outcome still has to follow the applicable rules. Implementation-defined does not mean “discover it by experimenting”; consult the implementation’s documentation. Undefined behavior is not a fourth arithmetic result waiting to be measured. An implementation may document extensions, but relying on one needs an explicit implementation contract.
2. Validate before an operation needs the guarantee
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
static bool read_element(const int *values, size_t count, size_t index, int *result)
{
if (values == NULL || result == NULL || index >= count) return false;
*result = values[index];
return true;
}
int main(void)
{
int values[] = { 2, 4, 6 };
int result = 99;
bool rejected = read_element(values, 3, 3, &result);
assert(!rejected && result == 99);
bool accepted = read_element(values, 3, 2, &result);
assert(accepted && result == 6);
return 0;
}
The check precedes both subscripting and reading the element. Checking after an out-of-bounds read would be too late. The function still relies on its caller: values must designate at least count readable int elements and result a writable int. A non-null pointer and an integer count are not proof of a live allocation, correct type, alignment, or truthful capacity.
Other violations include signed overflow, reading certain indeterminate values, using an object after its lifetime, invalid pointer arithmetic, incompatible type access, unsequenced conflicts, and data races. The following lessons develop those boundaries. Do not assign an “expected output” to such an invalid example. This unit runs defined examples and explicit build-rejection cases rather than deliberately executing UB.
3. A surprising value can be completely defined
unsigned int value = UINT_MAX;
value += 1U;
Unsigned arithmetic is reduced modulo one more than the maximum representable value. The wrap here is defined. That does not make it a correct allocation size or application result. Defined language behavior and a satisfied application specification are separate tests. Conversely, ordinary signed addition that exceeds its result type’s range has undefined behavior; a familiar CPU wrap is not its portable meaning.
4. A required diagnostic is a different question
A translation unit violating a syntax rule or constraint requires a diagnostic under the standard’s rules. That does not mean every UB-triggering runtime path requires one, nor that every diagnostic must stop translation. This intentionally invalid declaration initializes an int pointer from a nonzero integer without a permitted conversion; the checked strict build rejects it.
int *pointer = 7;
5. Tests provide evidence inside a contract
Warnings, sanitizers, assertions, reviews, and different builds find different defects. Their silence cannot establish all language requirements, all inputs, or all targets. Optimization may exploit valid-program assumptions; changing optimization is a useful investigation, not a repair for UB. Write down the operation’s preconditions and preserve them on every path.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 3.4, 5.1.1.3, 6.2.5p9, 6.5, 6.7.9. Stable core rules used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 6.2.6.2, 6.5. C23 notes are source-reviewed separately from C17 example checks.
A valid explanation starts with a valid operation
Compare, follow, and explain this idea
Undefined behavior means the C standard imposes no requirements for that situation. It is not a request to guess a surprising output. First ask whether each evaluated operation satisfies its contract.
When this helps Use this habit before tracing bounds, expired objects, arithmetic limits, and expressions with interacting side effects.
Read the ideas side by side
- Unspecified behavior
- The standard permits alternatives without requiring the implementation to document which one is chosen.
- Implementation-defined behavior
- A permitted choice must be documented by the implementation.
Both have language-defined boundaries; neither is a synonym for every possible outcome.
- Undefined behavior
- The standard imposes no requirements for the affected situation.
- Constraint violation
- A translation unit violates a constraint. A conforming implementation must issue at least one diagnostic for that unit.
A diagnostic is not necessarily a refusal to compile; not every undefined operation requires a diagnostic.
- A successful observed run
- Describes one run with one build and environment.
- A language guarantee
- Applies under the stated C rules and preconditions.
An observation alone does not prove that the program has defined behavior.
Follow the reasoning
Do the bounds check before any subscripted read. This example deliberately chooses the one-past index and takes a safe alternative.
C17 · illustrative fragments in the stated context
int values[3] = {3, 6, 9};size_t index = 3;if (index < 3) {/* values[index] may be read here */} else {/* handle the missing element */}
- Establish the valid indexes
The three-element array has indexes 0, 1, and 2.
- Read index as a value
index holds 3. Holding that integer value is not itself an invalid array access.
- Evaluate the guard
index < 3 is false. No array subscript has been evaluated to read an element yet.
- Skip the element access
The guarded branch is not executed. The program does not read values[3].
- Handle the missing element
The else branch reports no element. It supplies defined behavior for this case instead of relying on an out-of-range read.
Common misconceptions
These statements are misleading. Open each one to see why.
MisconceptionUndefined behavior means the program must crash at that line.
The standard promises no specific symptom or point of failure. A build can appear to work, fail, or behave differently after optimization.
MisconceptionTwo’s complement guarantees signed wraparound.
A representation rule does not define overflowing signed arithmetic. Check before computing when a signed result might exceed its type’s range.
MisconceptionA sanitizer proves the whole program has no undefined behavior.
A sanitizer checks supported conditions on executed paths. Tests and diagnostics help, but they do not cover every path or every language rule.
Go a little deeperOptional technical detail
Precedence does not establish evaluation order
Parentheses group an expression. They do not generally sequence its operands. Analyze i++ + i++ as an unsequenced side-effect conflict; do not run it to discover a portable answer.
Prevent the invalid operation, not just the visible result
A guard must be evaluated before the dangerous access or arithmetic. Reading values[index] first and checking index afterwards has already crossed the boundary.
C17 These bounds and sequencing rules apply to the C17 baseline. Keep the distinction between runtime undefined behavior and translation-time constraint diagnostics.
C23 C23 does not make out-of-bounds reads, accesses to expired objects, or unsequenced modifications safe. Two’s-complement representation still does not define signed arithmetic overflow.
Public committee drafts; clause references help you verify the explanation. N3096 is a C23 working draft.
Say it in your own words
Is merely storing index = 3 undefined for this three-element array?
Compare with an explanation
No. The integer value can be stored and tested. The guarded example avoids the invalid element access, so it can safely handle that value.
Before you move on
- Undefined, unspecified, and implementation-defined behavior describe different language categories.
- A language-valid operation can still violate an application’s requirements.
- Observing one result cannot establish a guarantee that the language does not provide.
Keep these ideas separate
- Undefined / Unspecified
- Undefined behavior supplies no standard requirements for that execution; unspecified behavior permits a choice among allowed possibilities.
How would you decide whether two observed outputs show an allowed choice or an invalid operation?
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
- That the operation is portable.
One observed outcome cannot create a language guarantee.
- Only that this run produced that observation.
✓ Correct reasoning. The C standard imposes no requirements for undefined behavior; a successful-looking run does not validate the operation.
- That the compiler must warn every time.
A diagnostic is not required for every possible undefined behavior.
C17
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.
These three categories, precisely defined by the C standard, describe situations where the standard doesn't fully pin down what happens — and confusing them is a common source of bugs that "work" on one compiler and fail on another.
- Undefined behavior (UB). The standard imposes no requirements on the execution. Examples include invalid pointer dereference, signed integer overflow, use of an indeterminate automatic
int, out-of-bounds element access, unsequenced conflicting accesses to a scalar object, or a data race. A crash or a diagnostic is not guaranteed. - Unspecified behavior. The standard permits more than one outcome and doesn't require an implementation to document which one it chose — for example, the order in which a function's arguments are evaluated.
- Implementation-defined behavior. Like unspecified behavior, except the implementation must document its choice — for example, the exact size of
intandlong, whether plaincharis signed, and the result of right-shifting a negative number.
The practical stakes are portability and correctness: code that happens to rely on undefined behavior may pass every test on the developer's own machine, yet fail unpredictably on a different compiler, optimization level, or hardware architecture — which is exactly why compiler warnings, sanitizers, and static analyzers (Section 32) are treated as essential tools rather than optional extras in serious C development.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.