YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Correctness & careChapter 58 of 73

Behavior, guarantees, and undefined behavior

Separate undefined, unspecified, and documented implementation choices, then justify the preconditions before an operation.

9 min readAdvancedC17 baseline
Offline reading
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

CategoryMeaning
Unspecified behaviorSeveral permitted choices; the implementation need not document which it chooses. Example: order of independent function arguments.
Implementation-defined behaviorA permitted implementation choice that must be documented. Example: plain char signedness or right shift of a negative signed value.
Undefined behaviorThe 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

Complete C17 program
#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

C17 · illustrative fragment
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.

C17 · intentional build rejection
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

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

  1. int values[3] = {3, 6, 9};
  2. size_t index = 3;
  3. if (index < 3) {
  4. /* values[index] may be read here */
  5. } else {
  6. /* handle the missing element */
  7. }
  1. Establish the valid indexes

    The three-element array has indexes 0, 1, and 2.

  2. Read index as a value

    index holds 3. Holding that integer value is not itself an invalid array access.

  3. Evaluate the guard

    index < 3 is false. No array subscript has been evaluated to read an element yet.

  4. Skip the element access

    The guarded branch is not executed. The program does not read values[3].

  5. 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.

Check the source rules

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.
Explain it in your own words

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.

A program with undefined behavior appeared to work once. What does that establish?
Read the explanation for every choice
  1. That the operation is portable.

    One observed outcome cannot create a language guarantee.

  2. 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.

  3. 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 int and long, whether plain char is 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.

CHAPTER 58 / 73

In this chapter

Behavior, guarantees, and undefined behavior

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