Skip to content
systemcoding.dev
Fundamentals

The Complete Guide to Undefined Behaviour in C

Learn what undefined behavior is in C, why compilers exploit it, the common kinds with sanitizer output, and how to write, detect and fix code that avoids it.

25 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the C, C++ and LLVM logos.

Undefined behavior is the part of C that separates a program that works from a program that has been shown to work. A function that returns the right answer at -O0 can return the wrong one at -O2. A null check can disappear. A loop can run forever, or never. A security fix can be deleted by the same compiler that built it. None of that is a compiler bug. It is the compiler doing exactly what the C standard allows once your program steps outside the rules, and the standard allows anything. This guide explains the idea from the ground up, shows the kinds of undefined behavior you meet in practice with real sanitizer messages, and gives a method for writing C that stays inside the rules. It targets C11 and C17 with GCC 14 and Clang 19 on Linux, and it flags where C23 changes things.

The claim to remember is this: undefined behavior is not an error that happens at the line you wrote, it is a promise you made to the compiler, and the compiler uses that promise to rewrite the rest of your program. Almost every section below is either a way the promise gets broken or a way to find out that it was.

What undefined behavior is

The C standard describes the behavior of a program in terms of an abstract machine. For most programs it says what the machine does. For some constructs it says nothing, and it says so on purpose. ISO/IEC 9899:2011 section 3.4.3 defines undefined behavior as "behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements". The note beneath it lists three permissible results: ignoring the situation with unpredictable results, behaving in a documented manner characteristic of the environment, and terminating translation or execution with a diagnostic. The note is informative, not a limit. "No requirements" means none.

Two consequences follow, and both surprise people who learned C by experiment.

First, the behavior is not confined to the offending operation. The standard defines conformance for a whole program execution. If an execution contains an undefined operation anywhere, nothing in the standard constrains any part of that execution, including the parts that ran before it. A compiler that proves an operation is undefined on some path may therefore assume that path never runs, and optimize everything leading to it.

Second, "it works on my machine" proves nothing. An undefined construct that compiles to sensible code today can compile to something else with the next compiler version, a different optimization level, a different target or a different surrounding function that changes inlining. The standard did not guarantee the sensible result, so no later version owes it to you.

Annex J.2 of C11 lists the situations the standard calls undefined. There are roughly two hundred entries. Most are obscure: a #include directive that expands to something unexpected, a call through a function type that does not match. A short list accounts for nearly all the bugs people hit, and this guide concentrates on that list.

Three kinds of "not defined"

The standard has three related terms, and mixing them up causes bad advice.

Implementation-defined behavior is behavior the standard leaves to the implementation, which must document its choice. The size of int, the result of right-shifting a negative number, and whether char is signed are implementation-defined. You can rely on the choice for a given compiler and target.

Unspecified behavior is behavior where the standard offers two or more possibilities and does not require the implementation to document which it picks. The order in which function arguments are evaluated is unspecified. The program is still valid, and any of the allowed results is correct.

Undefined behavior has no list of possibilities at all. A separate post compares the three in detail. Here the important point is the difference in kind: with the first two you may get a surprising value, but the program remains a valid program. With the third, there is no program to reason about.

Why C has it at all

C was designed to be implementable on every machine of the 1970s, from word-addressed minicomputers to machines with ones' complement arithmetic. Where hardware disagreed, the committee refused to pick a winner. Signed overflow wraps on two's complement hardware, saturates on some DSPs and traps on others, so the standard said nothing and each implementation did the cheapest thing.

That original reason has been joined by a second, which now matters more. If an operation cannot happen in a valid program, the compiler needs no code to handle it, and it can reason with stronger assumptions. A compiler that knows int addition never overflows can assume a loop counter never wraps and then vectorize, unroll and strength-reduce the loop. A compiler that knows a pointer is never null at a dereference can drop later checks. A compiler that knows two pointers of different types never refer to the same object can keep a value in a register across a store. These are the reasons C code compiles to fast machine code without runtime checks, and they are the reasons undefined behavior has teeth.

The cost is that the responsibility moves to you. The language does not check. It assumes you did.

How the compiler uses the promise

An example shows the mechanism better than a definition. This function reads a pointer and then checks it:

nullcheck.cc
int first_item(int *items) {
    int value = *items;
    if (items == NULL) {
        return -1;
    }
    return value;
}

Read it as a human and the intent is plain: return -1 for a null argument. Read it as the compiler does. The load *items on the first line is undefined if items is null, so after that line the compiler may assume items is non-null. Then items == NULL is always false, the branch is dead, and the function becomes a single load and return. GCC at -O2 on Linux does exactly this, using its -fdelete-null-pointer-checks optimization, which is on by default at -O2 and above for most targets. The Linux kernel was bitten by this pattern in 2009, in a bug where a dereference ahead of a check let the compiler delete the check and turned a null pointer fault into an exploitable hole. The kernel build now passes -fno-delete-null-pointer-checks.

The fix is to reorder, so that the check comes first:

nullcheck-fixed.cc
int first_item(int *items) {
    if (items == NULL) {
        return -1;
    }
    return *items;
}

Notice what the original did not do. It did not crash, it did not warn, and it passed review because every line looked reasonable. The compiler is not being malicious. It is applying a transformation that is valid for every program without undefined behavior, and yours was not one.

A second classic example is the overflow check that checks nothing:

overflow-check.cc
#include <limits.h>
#include <stdio.h>

static int will_not_overflow(int x) {
    return x + 1 > x;
}

int main(void) {
    printf("%d\n", will_not_overflow(INT_MAX));
    return 0;
}

Built with GCC 14 and -O0, the addition wraps to INT_MIN, the comparison INT_MIN > INT_MAX is false, and the program prints:

Text
0

Built with -O2, GCC reasons that x + 1 for signed x never overflows, so x + 1 > x is always true, and it folds the function to return 1. The program prints:

Text
1

The same source, the same input and two answers, both permitted. A programmer who wrote the check to detect overflow has written code that never detects it at the optimization level that ships.

The kinds you will actually meet

The sections below go through the undefined behaviors that produce most real bugs. Each one names the rule, shows the failure, shows what the sanitizer says about it, and gives the safe form. Sanitizer messages come from -fsanitize=undefined, introduced below, and the exact column numbers on your machine will match your own source.

Signed integer overflow

If the result of an arithmetic operation on a signed integer type cannot be represented in that type, the behavior is undefined (C11 6.5p5, "exceptional condition"). That covers +, -, *, unary minus, ++, and the division INT_MIN / -1. It does not cover unsigned arithmetic, which is defined to wrap modulo 2^N (6.2.5p9).

overflow.cc
#include <limits.h>
#include <stdio.h>

int main(void) {
    int x = INT_MAX;
    int y = x + 1;
    printf("%d\n", y);
    return 0;
}

Compile with gcc -fsanitize=undefined overflow.c and run it:

Text
overflow.c:6:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648

The runtime message goes to standard error and the program carries on, because UBSan's default is to report and continue. The second line is what this particular build printed after the report, and it is not guaranteed.

The safe forms are three. Use an unsigned type when you want wraparound, converting back carefully. Check before you operate, comparing against the limits. Or use the checked arithmetic builtins, which GCC 5 and Clang 3.8 added and C23 standardizes as ckd_add, ckd_sub and ckd_mul in <stdckdint.h>:

checked-add.cc
#include <limits.h>
#include <stdio.h>

int main(void) {
    int result;

    if (__builtin_add_overflow(INT_MAX, 1, &result)) {
        puts("overflow detected");
    } else {
        printf("sum = %d\n", result);
    }

    if (!__builtin_add_overflow(40, 2, &result)) {
        printf("sum = %d\n", result);
    }
    return 0;
}
Text
overflow detected
sum = 42

__builtin_add_overflow computes the true mathematical sum, stores the wrapped value in result and returns whether the true sum did not fit. It never invokes undefined behavior, whatever the operands.

Two related cases deserve a name. INT_MIN / -1 and INT_MIN % -1 are undefined, because the true quotient -INT_MIN does not fit, and on x86-64 the idiv instruction raises a hardware divide error that the kernel reports as SIGFPE. And abs(INT_MIN) is undefined for the same reason, a trap that has survived many hand-written parsers.

Division by zero

Dividing an integer by zero is undefined (6.5.5p5), and so is % by zero. On x86-64 it traps as SIGFPE. On ARM Cortex-A with the sdiv instruction it returns zero without any trap, so a program that crashes on one machine silently produces zero on another. UBSan reports it:

Text
div.c:5:15: runtime error: division by zero

Floating-point division by zero is a different matter. On targets with IEEE 754 arithmetic, 1.0 / 0.0 produces infinity and is defined by Annex F when the implementation claims conformance, which GCC does on common targets.

Shifts

A shift is undefined when the right operand is negative or is greater than or equal to the width of the promoted left operand (6.5.7p3). A left shift of a negative value is undefined, and a left shift of a positive signed value whose result does not fit is undefined too. In C, 1 << 31 for a 32-bit int is undefined because the true result 2,147,483,648 does not fit. C23 and C++20 changed the rules for some of these, but code written for C11 should assume the strict reading.

shift.cc
#include <stdio.h>

int main(void) {
    int n = 32;
    unsigned int mask = 1u << n;
    printf("%u\n", mask);
    return 0;
}
Text
shift.c:5:28: runtime error: shift exponent 32 is too large for 32-bit type 'unsigned int'

On x86-64 the hardware masks the shift count to five bits for a 32-bit operand, so a naive build prints 1 after the report: 1u << 32 behaves like 1u << 0. On ARM a variable shift of 32 usually gives 0. Both behaviors are legal because neither is required.

The safe pattern is to validate the count (n >= 0 && n < 32) or to mask it yourself (n & 31) when you want the hardware behavior on purpose. Always shift unsigned values when you are doing bit manipulation, and write the constant as 1u rather than 1.

Out-of-bounds array access and pointer arithmetic

Computing a pointer more than one element past the end of an array, or before its start, is undefined even if you never dereference it (6.5.6p8). Dereferencing a pointer to one past the end is undefined. Indexing a[i] is defined as *(a + i), so an out-of-range index falls under both rules.

bounds.cc
#include <stdio.h>

int main(void) {
    int a[4] = {10, 20, 30, 40};
    int i = 4;
    printf("%d\n", a[i]);
    return 0;
}

With -fsanitize=bounds (included in -fsanitize=undefined):

Text
bounds.c:6:20: runtime error: index 4 out of bounds for type 'int [4]'

Without the sanitizer the program prints whatever sits after the array on the stack, which may be a stale value, the neighboring variable i, or part of a saved register. The related post on why out-of-bounds access sometimes appears to work explains why a read that looks harmless is still undefined. A write can corrupt a neighbor, a return address or a heap chunk header, and that is the root of most stack and heap buffer overflow vulnerabilities.

UBSan's bounds check only knows the size of arrays whose type carries it. A char * that points into a buffer has no declared size, so the sanitizer cannot catch an overrun through it. For that, AddressSanitizer (-fsanitize=address) tracks allocations and red zones, and reports stack-buffer-overflow, heap-buffer-overflow or global-buffer-overflow with the access and the allocation site.

Null and invalid pointer dereference

Dereferencing a null pointer is undefined (6.5.3.2p4). So is dereferencing a pointer to an object whose lifetime has ended, a pointer produced by arithmetic outside an array, or a pointer converted from an integer that does not name a valid object. UBSan flags null and misaligned pointers, and AddressSanitizer flags the lifetime errors. The separate post on null explains why Linux turns the null case into a segmentation fault and why that is not guaranteed.

Text
null.c:7:16: runtime error: load of null pointer of type 'int'

When the pointer is a struct, the message becomes member access within null pointer of type 'struct item', which makes the field access obvious.

Use after free, double free and invalid free

After free(p) the pointer value is indeterminate (6.2.4p2), and using it, even to compare it, is undefined. Passing the same pointer to free twice is undefined (7.22.3.3). Passing free a pointer that did not come from malloc and its relatives is undefined.

uaf.cc
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(sizeof *p);
    if (!p) return 1;
    *p = 7;
    free(p);
    printf("%d\n", *p);
    return 0;
}

AddressSanitizer reports this precisely, with the allocation and free stacks:

Text
==4120==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010 at pc 0x55d3c4e2a1f8 bp 0x7ffd1a6c1a10 sp 0x7ffd1a6c1a00
READ of size 4 at 0x602000000010 thread T0
    #0 0x55d3c4e2a1f7 in main uaf.c:9

Addresses and process ids differ per run. The one habit that prevents most of these is assigning p = NULL after free(p), which turns a later use into a null dereference that crashes in a predictable place, and makes a second free(p) a defined no-op.

Reading uninitialized variables

A variable with automatic storage duration and no initializer holds an indeterminate value. Reading it is undefined for most types (6.3.2.1p2, and 6.7.9p10 for the value itself), and the compiler treats the value as whatever is convenient. It can pick a different value at each use in the same function.

uninit.cc
#include <stdio.h>

int main(void) {
    int total;
    for (int i = 0; i < 3; i++) {
        total += i;
    }
    printf("%d\n", total);
    return 0;
}

GCC with -Wall -O2 warns 'total' is used uninitialized here, and the output of the program can be any integer. The tools that catch the run-time case are MemorySanitizer in Clang (-fsanitize=memory), which reports use-of-uninitialized-value, and Valgrind's Memcheck on GCC builds. Initialize at declaration. Where that costs performance in a hot path, measure first; it almost never does. GCC 12 and Clang 8 offer -ftrivial-auto-var-init=zero, a hardening option that zero-fills automatic variables, which hides the bug in production rather than fixing it.

Violating strict aliasing

C11 6.5p7 lists the lvalue types through which an object may be accessed: its declared type, a compatible or qualified version, a signed or unsigned variant, a struct or union containing it, and a character type. Reading a float object through an int lvalue is not on the list, so it is undefined. Compilers use the rule to assume that a float * and an int * never refer to the same memory.

alias.cc
#include <stdio.h>
#include <stdint.h>

static uint32_t float_bits(float f) {
    return *(uint32_t *)&f;     // undefined: accesses a float through uint32_t
}

int main(void) {
    printf("0x%08x\n", float_bits(1.0f));
    return 0;
}

At -O0 this typically prints 0x3f800000. At -O2 GCC may still print that, or may reorder the load before the store of f into memory and print garbage, and the result can differ by version and by whether the function was inlined. UBSan has no check for aliasing, and -Wstrict-aliasing catches only the easy cases. The portable fix is memcpy, which compilers turn into a register move:

alias-fixed.cc
#include <stdio.h>
#include <stdint.h>
#include <string.h>

static uint32_t float_bits(float f) {
    uint32_t u;
    memcpy(&u, &f, sizeof u);
    return u;
}

int main(void) {
    printf("0x%08x\n", float_bits(1.0f));
    return 0;
}
Text
0x3f800000

A union also works in C, as shown in the post on unions. Character types are the exception that lets you inspect any object byte by byte through an unsigned char *, which is how memcpy itself is implemented.

Misaligned access

Converting a pointer to a type with stricter alignment than the object it came from is undefined if the result is misaligned (6.3.2.3p7). The practical form is casting a byte buffer to uint32_t *, which runs on x86-64 and faults on small ARM cores. UBSan with -fsanitize=alignment reports load of misaligned address 0x7ffc1f2a3b11 for type 'uint32_t', which requires 4 byte alignment. The fix is memcpy into a local, as above.

Modifying a string literal or a const object

Attempting to modify a string literal is undefined (6.4.5p7), and so is modifying an object defined with const (6.7.3p6), even through a cast that removes the qualifier. On Linux the literal lives in a read-only page, so the write faults. A const global lives there too. The bug is obscured by the type, since char *s = "text" compiles without a warning in C unless you use -Wwrite-strings, so declare such pointers const char *.

Unsequenced side effects

Modifying a scalar twice between sequence points, or modifying it and reading it other than to compute the new value, is undefined (6.5p2). i = i++ + 1 and a[i] = i++ are the textbook cases. A separate post covers sequence points and the C11 wording in detail; the rule of thumb is one modification of a given object per expression, and no other use of it in the same expression except to compute that modification.

Data races

If two threads access the same non-atomic object without synchronization and at least one writes, the behavior is undefined (C11 5.1.2.4p25). The result is more than a torn read. The compiler is entitled to assume no other thread changes a plain variable, so a loop that waits on a plain int flag can read it once and spin forever. A later post covers the C11 memory model. For now: shared mutable state needs _Atomic or a mutex, and volatile is neither. ThreadSanitizer (-fsanitize=thread) finds races at run time.

Calling through the wrong type and missing return values

Calling a function through a pointer of an incompatible function type is undefined (6.5.2.2p9). Flowing off the end of a non-void function and then using its return value is undefined (6.9.1p12), which is why -Wreturn-type, on by default in GCC 8 and later, is worth treating as an error. Passing a wrong argument type to a variadic function, such as printf("%d", 1.5), is undefined, and -Wformat checks it for printf family calls.

Overlapping copies and restrict violations

memcpy with overlapping source and destination is undefined (7.24.2.1p2), and memmove exists for that case. Passing overlapping pointers to a function that declares them restrict is undefined as well, because the qualifier is a promise that the objects do not alias.

Infinite loops without side effects

C11 6.8.5p6 lets the implementation assume that an iteration statement whose controlling expression is not a constant expression, and whose body does no input or output, volatile access, atomic operation or synchronization, terminates. A loop like while (n != 1) n = collatz(n); can therefore be removed if the compiler cannot see output. A constant controlling expression, such as while (1), is exempt, which is why embedded main loops written that way are safe. C++ has a broader form of the rule, and Clang applies it more aggressively there.

Detecting it: warnings, sanitizers and tools

No single tool finds everything. Use them in layers.

Compiler warnings cost nothing. Build with -Wall -Wextra plus -Wconversion and -Wshadow as your code allows, and add -Wnull-dereference, -Wstrict-aliasing=2 and -Wformat=2. GCC's -Wmaybe-uninitialized and -Warray-bounds depend on optimization, so they run best with -O2. Treat warnings as errors in CI with -Werror for a set you have already cleaned.

UndefinedBehaviorSanitizer instruments the code to check for undefined operations as they run. Build with -fsanitize=undefined, which enables, among others, signed-integer-overflow, shift, integer-divide-by-zero, bounds, alignment, null, unreachable, vla-bound and object-size. Add -fno-sanitize-recover=undefined to make the first report abort the program, which is the right mode for tests. Each check adds code and run time, so UBSan builds are for testing and fuzzing, not for production, though Clang's -fsanitize-minimal-runtime is small enough for some deployments. A dedicated post walks through UBSan options; here the point is that it reports only on paths your tests execute.

AddressSanitizer covers the memory errors UBSan cannot see: heap, stack and global buffer overflows, use after free, use after return (with an option) and double free. Build with -fsanitize=address -fno-omit-frame-pointer -g. It roughly doubles memory use and slows execution by a factor the AddressSanitizer documentation puts around two. Do not combine it with ThreadSanitizer in one build.

MemorySanitizer (Clang only) finds reads of uninitialized memory. It requires every library the program uses to be instrumented, which makes it harder to adopt than the others, and it works on Linux x86-64 and a few other targets.

ThreadSanitizer finds data races on the paths that run, using happens-before analysis. Build with -fsanitize=thread.

Valgrind Memcheck needs no recompilation and catches invalid reads and writes, leaks and uninitialized use, at roughly an order of magnitude slowdown. It is useful when you cannot rebuild.

Static analyzers such as the Clang Static Analyzer (scan-build), GCC's -fanalyzer (introduced in GCC 10 for C, with tracking of malloc state, null dereferences and use after free), and commercial tools reason over code without running it. They produce false positives and miss things, but they cover paths your tests do not reach.

Fuzzing drives the other tools. A fuzzer such as libFuzzer or AFL++ generates inputs, and a build with UBSan and AddressSanitizer turns each undefined operation into a crash the fuzzer can detect and minimize. This pairing finds the bugs that matter most, the ones triggered by hostile input.

A clean sanitizer run proves only that the executed paths contain no violations that the enabled checks can detect. It is evidence, not a proof of absence.

Writing code that stays inside the rules

Detection is a safety net. The goal is to write code where the rules are hard to break. A short set of habits carries most of the weight.

Use unsigned types for bit patterns and wraparound, signed types for quantities. Hash functions, checksums, bit masks and flags want modulo arithmetic and well-defined shifts, which unsigned types provide. Sizes, counts and indexes should use size_t or ptrdiff_t, and be checked before arithmetic that could exceed their range.

Check before you compute. The test if (a > INT_MAX - b) is defined for non-negative operands, while if (a + b < a) is not. Use __builtin_*_overflow or ckd_* when the operation matters. Allocation sizes especially: malloc(n * sizeof(T)) with a hostile n must use a checked multiplication or calloc, which does the check for you.

Initialize everything at declaration. int total = 0;, struct config cfg = {0};, and designated initializers make uninitialized reads impossible by construction.

Keep pointer lifetimes short and ownership explicit. Decide who frees each allocation, set freed pointers to NULL, and prefer passing a pointer and a length together over a bare pointer.

**Use memcpy for reinterpretation.** It handles aliasing and alignment at once, and the compiler removes the call.

Write checks before the operation they guard. Validate arguments at the top of the function. Do not read the value and then test the pointer.

Prefer the standard library's checked interfaces where they exist. snprintf over sprintf, strnlen for untrusted lengths, fgets over gets, strtol with errno over atoi. They remove whole classes of bounds errors.

A snippet that applies several of these habits at once, an index lookup that cannot overflow, read out of bounds, or be misused after free:

safe-index.cc
#include <stddef.h>
#include <stdio.h>

static int get_item(const int *items, size_t count, size_t index, int *out) {
    if (items == NULL || out == NULL || index >= count) {
        return -1;
    }
    *out = items[index];
    return 0;
}

int main(void) {
    const int items[] = {10, 20, 30};
    int value = 0;

    if (get_item(items, 3, 1, &value) == 0) {
        printf("items[1] = %d\n", value);
    }
    if (get_item(items, 3, 7, &value) != 0) {
        puts("index 7 rejected");
    }
    return 0;
}
Text
items[1] = 20
index 7 rejected

The index is size_t, so it cannot be negative, the single comparison covers both ends of the range, the null checks come before any dereference, and the result goes out through a pointer while the return value reports failure. None of this is clever. It simply never forms an invalid pointer.

Compiler flags that change the rules

Some flags turn selected undefined behaviors into defined ones, at a cost in optimization. They are not a substitute for fixing the code, but they are the practical choice for a codebase too large to audit.

FlagEffectTypical cost
-fwrapvsigned overflow wraps in two's complementblocks some loop optimizations
-fno-strict-aliasinglets any lvalue alias any otherblocks type-based alias optimizations
-fno-delete-null-pointer-checksa null dereference no longer proves non-nullkeeps redundant checks
-ftrivial-auto-var-init=zerozero-fills automatic variablessmall run-time and size cost
-fsanitize=undefined -fsanitize-trap=undefinedtraps on the first violationextra code

The Linux kernel builds with -fno-strict-aliasing, -fno-delete-null-pointer-checks and -fwrapv, among others, and says so in its documentation. That is a defensible engineering decision for a codebase of its size and history. For new code, the better position is to make the code correct and keep the optimizer's freedom. A later post in this series covers these three flags and when each is worth its cost.

Where this guide's position is contested

Not everyone agrees that compilers should exploit undefined behavior the way they do. One camp, which includes many kernel and systems programmers, argues that the standard's "no requirements" was meant to give implementations room to do the natural thing on their hardware, not to license deleting security checks, and that a compiler should treat signed overflow as wrapping and a null dereference as a trap. The "friendly C" proposals, and some compiler flags, come from that view. The other camp, which includes the compiler maintainers, argues that the optimizations are what make C competitive, that every optimization that relies on undefined behavior is valid, and that compilers cannot read intent: from inside the optimizer "the programmer meant to wrap" and "this path is impossible" look the same.

We side with the second camp on the engineering question and with the first on the policy one. The compiler cannot guess, so you have to say what you mean: write code that does not rely on a particular undefined result, use the checked and wrapping constructs the language gives you, and turn on sanitizers so the cases you missed fail loudly. And where you inherit a large codebase that depends on wrapping or aliasing, build it with the flags above and move on rather than argue.

A short list of what to do on Monday

Compile every project with -Wall -Wextra and read the warnings. Add a CI job that builds the test suite with -fsanitize=address,undefined -fno-sanitize-recover=undefined and runs it. Add a fuzz target for every function that parses input. Replace unchecked size arithmetic that feeds malloc with checked forms. Initialize every automatic variable at declaration. And read each sanitizer report as a promise broken, not as noise, because the program that printed the right answer last week is not guaranteed to print it next week.

Boundaries: when this advice does not fit

The advice here assumes hosted or freestanding C compiled with a mainstream compiler. A few situations are different. If you compile for a vendor toolchain that documents a stronger guarantee, such as a compiler that defines signed overflow as wrapping by default, you may rely on that guarantee, and say so in a comment next to the code that depends on it. If you write a language runtime or a kernel and need exact control over memory, you will use constructs that are formally undefined, such as pointer-to-integer round trips and type punning, and you should confine them to a few well-reviewed functions and compile with the flags that make them behave. And if you work in safety-critical code under MISRA C or CERT C, the coding standards list prohibited constructs that map closely to the undefined behaviors above, and your toolchain's certification evidence replaces some of the testing advice.

Rust, and C++ with its own set of undefined behaviors, shift the picture. Safe Rust has none by construction, and unsafe blocks have their own list, which Miri can check. C++ has the same signed overflow, null and bounds rules as C, adds undefined behavior for violating the one-definition rule and for lifetimes of non-trivial objects, and has no flexible aliasing escape other than std::memcpy and, since C++20, std::bit_cast.

Time travel: undefined behavior reaches backward

A claim that startles people is that undefined behavior can affect code that runs before the faulty operation. It follows directly from the definition. The standard constrains an execution as a whole, so if an execution contains an undefined operation, the compiler is free to assume that no input leading to one is ever supplied.

travel.cc
#include <stdio.h>

static int table[4] = {1, 2, 3, 4};

static int lookup(int i) {
    printf("looking up %d\n", i);
    return table[i];
}

int main(void) {
    return lookup(4) != 0;
}

The printf call comes before the out-of-bounds read. A reader expects the line looking up 4 to appear and then something odd to happen. A compiler that sees through the call chain may notice that lookup(4) always indexes past the end, conclude that main can only be reached on a path that never runs, and compile the whole body into a trap or into nothing at all. GCC emits a warning here with -Warray-bounds at -O2, and in practice both outcomes appear across versions: some builds print the line and then read garbage, and others print nothing. The standard promises neither. This is the practical meaning of "no requirements", and it is why you cannot debug an undefined behavior bug by putting printf calls near the suspected line. The observation changes the program.

Undefined behavior and security

Most memory-safety vulnerabilities are undefined behavior with an attacker attached. A stack buffer overflow is an out-of-bounds write. A use after free is a lifetime violation. An integer overflow in a size calculation leads to a short allocation and then to an out-of-bounds write. A type confusion in a tagged union is a strict-aliasing or tag violation. The reason the same bug class keeps recurring is that C leaves checking to the programmer and gives the optimizer no reason to add any.

That also explains the shape of the mitigations. Stack protectors, _FORTIFY_SOURCE, control-flow integrity, address space layout randomization and non-executable stacks do not remove undefined behavior. They make the usual consequences harder to exploit. The sanitizers remove it during testing. And languages with a safe subset remove whole classes of it by construction, which is why new systems code is increasingly written in Rust or Zig with explicit unsafe regions, while existing C stays in service with the tooling described here wrapped around it.

A debugging workflow for a suspected case

When a program misbehaves only in optimized builds, treat undefined behavior as the first suspect rather than the last. A short sequence finds most cases.

  1. Rebuild with -O0 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined and run the failing input. If a report appears, you are done: read the file, line and message.

  2. If nothing appears, rebuild at the optimization level that fails, with the same sanitizers. Some violations are visible only after inlining.

  3. Add -Wall -Wextra -Wuninitialized -Warray-bounds=2 -Wnull-dereference at -O2 and read every new warning in the files involved.

  4. Run the failing input under Valgrind Memcheck, which sees uninitialized reads and heap errors without recompilation.

  5. If the bug depends on the compiler, bisect the flags. Turning off one optimization, such as -fno-strict-aliasing or -fno-delete-null-pointer-checks, and seeing the bug disappear tells you which rule the code is breaking, even before you find the line.

  6. For a bug in someone else's code, compare the disassembly. gcc -S -O2 shows the function with and without the suspect flag, and a missing check or a folded comparison is usually visible in a few lines of assembly.

The point of the bisection step is that a flag is a probe, not a fix. Once it points at the rule, fix the code so the flag is no longer needed.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.