Programming Search⌘K

Conceptcore

Undefined behavior

Also called UB, undefined behaviour.

Behavior for which the standard imposes no requirements. In C and C++ it covers errors such as signed overflow, and compilers optimize on the assumption that it never happens.

Applies to
core-languages

Idea

A language standard says what each program means. For some programs, it chooses to say nothing. The C standard defines undefined behavior as "behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this document imposes no requirements".1 The C++ standard uses almost the same words: "behavior for which this document imposes no requirements".2 Signed integer overflow, the dereference of a null pointer, a read past the end of an array and a read of freed memory are all undefined in both languages.

"No requirements" is meant literally. The implementation may ignore the situation and give an unpredictable result. It may document a behavior. It may also stop the translation or the execution with a diagnostic.1 A program with undefined behavior can print the right answer in a debug build, a wrong answer in an optimized build, and crash with a different compiler. None of these results is a bug in the compiler.

The C example below adds 1 to INT_MAX. It is built with UndefinedBehaviorSanitizer, which stops the program at the overflow. Without the sanitizer, the program has no defined output, so the page shows none.

This code has a memory error, on purpose, and the sanitizer reports it.

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

int main(void) {
    int balance = INT_MAX;
    int deposit = 1;
    printf("%d\n", balance + deposit);
}

Undefined behavior exists for two reasons. Some errors are expensive or impossible to detect on every machine, such as a pointer to freed memory. And when the standard does not fix a result, each compiler can use the fastest instruction of each machine. The C Rationale says that undefined behavior "gives the implementor license not to catch certain program errors that are difficult to diagnose", and that it marks places where an implementation may extend the language.6

How it works

Three kinds of freedom

The C and C++ standards give an implementation three different kinds of freedom. The difference matters, because only one of them makes a program wrong.

Kind What the standard says Example
Implementation-defined two or more behaviors are allowed; each implementation documents its choice the result of a right shift of a negative signed integer; sizeof(int)
Unspecified two or more behaviors are allowed; the implementation need not document or repeat its choice the order in which the arguments of a function call are evaluated
Undefined no requirements signed overflow; the dereference of a null pointer

C defines implementation-defined behavior as "unspecified behavior where each implementation documents how the choice is made". Its example is the propagation of the high-order bit when a signed integer is shifted right. Unspecified behavior allows two or more possibilities with no further requirement on which one is chosen, and its example is the order of evaluation of the arguments.3 C++ uses the same three terms. Its examples are sizeof(int) for an implementation-defined parameter, the order of evaluation of the arguments for an unspecified aspect, and a change to a const object for an undefined operation.4

A program that depends on implementation-defined behavior is correct but not portable. A program that depends on unspecified behavior is correct only if every allowed result is acceptable. A program with undefined behavior is not correct. The C standard says that a strictly conforming program produces no output that depends on any of the three kinds.5

C marks undefined behavior in three ways: the words "undefined behavior", a "shall" outside a constraint that the program breaks, and the omission of any definition. The standard says that there is "no difference in emphasis" among the three.5 Annex J lists the cases: J.1 for unspecified behavior, J.2 for undefined behavior and J.3 for implementation-defined behavior.3

Some cases from the C standard

  • Arithmetic. "If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined."7 Signed overflow and division by zero are such conditions. Unsigned arithmetic does not overflow. It wraps modulo 2ⁿ.
  • Shifts. A shift by a negative amount, or by an amount equal to or greater than the width of the promoted left operand, is undefined. A left shift of a signed value is undefined if the value is negative or if the result does not fit. A right shift of a negative signed value is implementation-defined.7 Machines differ here: x86 masks a 32-bit shift amount to 5 bits, and PowerPC masks it to 6 bits.8
  • Pointers. The unary * operator on an invalid pointer is undefined. The invalid values include a null pointer, an address that is not aligned for the type, and the address of an object after the end of its lifetime.7 NULL pointer dereference, Use after free and Out-of-bounds write are weaknesses that come from these rules.
  • Order. Two side effects on the same object that are not sequenced relative to each other, such as i++ + i++, are undefined.7

A whole execution has no meaning

The C++ standard describes the semantics with an abstract machine. An implementation needs to emulate only the observable behavior of this machine, which is the "as-if" rule. Then it says: if an execution contains an undefined operation, the standard "places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation)".4 The undefined operation does not only make its own result unknown. It removes every requirement on the execution, before and after it.

A note in the C standard limits this for C. Observable behavior that happens before an operation with undefined behavior appears as specified.1 Output that the program has already written stays written. But the compiler can still move or delete code that has no observable effect.

Why compilers assume that UB never happens

An optimizer must keep the meaning of every program. When an operation is undefined for some inputs, the optimizer needs to keep the meaning only for the other inputs. In practice, it assumes that the program never executes undefined behavior, and it uses that assumption as a fact.

  • Signed overflow. Because INT_MAX + 1 is undefined, the compiler may fold x + 1 > x to true and x * 2 / 2 to x. In a loop for (i = 0; i <= n; ++i) with a signed i, it may assume that the loop runs exactly n + 1 times. If overflow wrapped, the loop could be infinite when n is INT_MAX, and the compiler would have to give up the loop optimizations.8 Lattner names a cost of defined overflow on 64-bit targets: many sign extensions inside loops that use int as an index.8
  • A null check after a dereference. If a function dereferences p and then tests p == NULL, the compiler may reason that p cannot be null at the test, because the dereference would have been undefined. GCC documents this as -fdelete-null-pointer-checks, enabled by default on most targets: "if a pointer is checked after it has already been dereferenced, it cannot be null".9 Lattner shows that the result depends on the order of passes. If dead code elimination runs first, the unused load goes away and the check stays. If redundant null check elimination runs first, the check goes away.11
  • Type-based aliasing. C forbids access to an int object through a float lvalue. The compiler may then assume that a store through a float * does not change an int variable. This allows Clang to turn a loop that zeros an array of float into one call of memset.8 GCC turns on -fstrict-aliasing at -O2, -O3 and -Os.9
  • Loops with no effect. C++ lets the implementation assume that every thread eventually terminates, calls a library I/O function, accesses a volatile object or performs a synchronization or atomic operation. A note says this is intended to allow the removal of empty loops, even when termination cannot be proven.13

Each of these steps is valid alone. Together, they can turn a small error into a large change. The optimizer does not detect the undefined behavior and act on it. It uses the absence of undefined behavior as a premise, and the program breaks the premise.

A real case: the TUN driver

In 2009, Brad Spengler published an exploit for the TUN driver of Linux 2.6.30. The function tun_chr_poll read tun->sk and then tested if (!tun). GCC removed the test, by default, because the pointer had already been dereferenced. An attacker who mapped the page at address zero could then get into the body of the function with a null tun pointer.12 GCC keeps such checks when the option -fno-delete-null-pointer-checks is given.9

The second C example shows the same pattern, caught by the sanitizer before any optimizer can act on it.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stddef.h>
#include <stdio.h>

struct device {
    int flags;
};

int poll_flags(struct device *dev) {
    int flags = dev->flags; // dereference
    if (dev == NULL) {      // too late: the compiler may delete this
        return -1;
    }
    return flags;
}

int main(void) {
    struct device d = {3};
    printf("%d\n", poll_flags(&d));
    printf("%d\n", poll_flags(NULL));
}

Detection: sanitizers

A sanitizer is a compiler mode that adds checks to the generated code. The program runs as usual, and the run-time library reports the first error that a check finds.

  • UndefinedBehaviorSanitizer (-fsanitize=undefined) checks, among others, array subscripts with a static bound, shifts out of range, misaligned and null pointer dereferences, signed integer overflow and float-to-integer conversions that overflow. For most checks, it prints a report and continues. With -fno-sanitize-recover, it prints the report and exits.14 Its reports start with runtime error:, for example "signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'".14 A minimal runtime exists for use in production.14
  • AddressSanitizer (-fsanitize=address) detects out-of-bounds accesses to the heap, the stack and globals, use after free, use after return, double free and memory leaks. Its typical slowdown is 2x. Its runtime is not meant for production executables, because it was not built with security in mind.15

A sanitizer only checks the paths that a test executes. A clean run shows that this input had no undefined behavior that the checks know. It does not prove that the program has none. Data races need a third mode, ThreadSanitizer (-fsanitize=thread).33

Detection: constant evaluation

C++ requires the compiler to reject an operation with undefined behavior in a constant expression.162 A constexpr function that overflows compiles to unchecked code for a run-time call. The same function, called in a static_assert, is a compile error. See the C++ example file.

In languages

LanguageVerdictNote
PythonAbsent
C++Native
JavaAbsent
CNative
C#Native
JavaScriptAbsent
TypeScriptAbsent
GoAbsent
RustNative
KotlinAbsentKotlin on the JVM has the defined integer overflow and the bounds checks of Java; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLAbsentA query has no pointers and no access to raw memory.
BashAbsentThe shell has no pointers and no access to raw memory.
PowerShellAbsentPowerShell runs managed .NET code and has no pointer operations; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no arithmetic and no memory access.
CSSDoes not applyStyle rules have no memory access.
Regular expressionsDoes not applyA pattern has no arithmetic and no memory access.

The example files show the same errors in each language: a signed overflow, an index past the end, and the explicit way to check. The table gives the verdict for each tier 1 language.

Language Verdict Form
C native the term of the standard; Annex J.2 lists the cases
C++ native the term of the standard; constant evaluation rejects it
Rust native only in unsafe code; safe code panics or wraps
C# native only in unsafe code; safe code wraps or throws
Go absent overflow wraps and indexes are checked; unsafe and multiword races are the exceptions
Java absent every operation has a result or throws; races are limited by the memory model
Python absent unlimited integers; errors raise exceptions
JavaScript absent every operation has a result; some results are implementation-defined
TypeScript absent as JavaScript
Kotlin absent the rules of the JVM
PowerShell absent managed .NET code
Bash absent no pointers and no raw memory
SQL absent no pointers and no raw memory
Regex n/a a pattern has no arithmetic
HTML/CSS n/a no arithmetic and no memory access

Rust keeps undefined behavior, but only unsafe code can cause it. The Reference lists the behaviors that are undefined, among them data races, access through a dangling or misaligned pointer, a break of the aliasing rules and the production of an invalid value. It says: "unsafe only means that avoiding undefined behavior is on the programmer".18 Integer overflow is not on that list. It panics when debug assertions are on, and otherwise it may panic or wrap.19 The operations that only unsafe code may use are few: the dereference of a raw pointer, access to a mutable static, access to a union field, a call to an unsafe function, the implementation of an unsafe trait, and a few more.20 The Rustonomicon states the result: if all your code is safe Rust, you "will never endure a dangling pointer, a use-after-free, or any other kind of Undefined Behavior".21 The Reference puts the duty on the author of the unsafe code: no safe code that uses it may be able to trigger undefined behavior. Code that meets this duty is sound, and code that does not is unsound.18

C# has the same split. Safe code wraps on overflow by default, and checked turns overflow into System.OverflowException.27 In unsafe code, the specification uses the words of C: if a pointer has an invalid value, the behavior of * is undefined, and an out-of-bounds pointer element access is undefined.26

Go defines signed overflow. The specification says that "a compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true."22 Package unsafe allows operations that violate the type system.22 The memory model limits data races: a read of a single machine word must see a value that some write stored. This makes Go "less like C and C++, where the meaning of any program with a race is entirely undefined". A race on a value of several words, such as a slice, a string or an interface, can still lead to arbitrary memory corruption.23

Java gives integer overflow a result: the low-order bits of the true sum in two's complement.24 A data race can give surprising results, but it cannot make the semantics of other operations wrong, for example the length of an array.25

JavaScript has no undefined behavior in this sense, but it has implementation-defined results. The sort order of Array.prototype.sort is implementation-defined if the comparator is not consistent.28 Python integers have an unlimited range, subject only to memory.29 The ctypes module is the exception: it reaches the memory of the process directly, and its documentation warns that incorrect use can corrupt data or crash the process.36

PythonGitHub
x = 2**31 - 1
print(x + 1)
print(2**100)

try:
    [1, 2, 3][3]
except IndexError as e:
    print("IndexError:", e)
Output
2147483648
1267650600228229401496703205376
IndexError: list index out of range
  • Verdict: absent. Python integers have an unlimited range, so integer arithmetic never overflows.
  • An index out of range raises IndexError. Each error that C leaves undefined becomes an exception in Python.
  • The ctypes module runs outside these rules. Its documentation warns that incorrect use can corrupt data or crash the process.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <climits>
#include <iostream>

// An optimizer may fold this to "return true".
bool can_increment(int x) {
    int next = x + 1;
    return next > x;
}

int main() {
    std::cout << can_increment(1) << '\n';
    std::cout << can_increment(INT_MAX) << '\n';
}

The test next > x, where next is x + 1, looks like an overflow check, but it is not one. For every x where the addition is defined, the result is true. The compiler may assume that the addition is defined, so it may replace the whole function with true. UndefinedBehaviorSanitizer reports the overflow at the second call.

This code does not compile, on purpose.

#include <climits>

constexpr int next(int x) {
    return x + 1;
}

static_assert(next(41) == 42);
static_assert(next(INT_MAX) > 0); // not a constant expression

int main() {}

In a constant expression, the compiler must reject an operation that has undefined behavior. The same function that compiles to unchecked code at run time is checked during constant evaluation.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3};
    int sum = 0;
    for (std::size_t i = 0; i <= v.size(); ++i) { // <= reads one past the end
        sum += v[i];
    }
    std::cout << sum << '\n';
}

operator[] does not check the index. AddressSanitizer reports a heap-buffer-overflow at the read of v[3].

#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

bool can_increment(int x) {
    return x < std::numeric_limits<int>::max(); // test before the addition
}

int main() {
    std::cout << std::boolalpha;
    std::cout << can_increment(1) << ' ' << can_increment(std::numeric_limits<int>::max()) << '\n';
    std::vector<int> v = {1, 2, 3};
    try {
        std::cout << v.at(3) << '\n';
    } catch (const std::out_of_range&) {
        std::cout << "at(3) threw std::out_of_range\n";
    }
}
Output
true false
at(3) threw std::out_of_range
  • Verdict: native. The C++ standard defines undefined behavior in [defns.undefined] and gives the rule for a whole execution in [intro.abstract].
  • A check for overflow must come before the operation. Compare against std::numeric_limits<int>::max() minus the other operand.
  • v.at(i) checks the index and throws std::out_of_range. v[i] does not check it.
  • A constexpr function called in a constant expression is a cheap way to test code for undefined behavior at compile time, for the inputs that the test uses.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        int x = Integer.MAX_VALUE;
        System.out.println(x + 1);
        try {
            System.out.println(Math.addExact(x, 1));
        } catch (ArithmeticException e) {
            System.out.println(e);
        }
        int[] a = {1, 2, 3};
        try {
            System.out.println(a[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
-2147483648
java.lang.ArithmeticException: integer overflow
Index 3 out of bounds for length 3
  • Verdict: absent. The Java Language Specification gives a result for each operation. Integer addition that overflows gives the low-order bits of the true sum in two's complement.
  • Math.addExact throws ArithmeticException when the result overflows an int.
  • An index out of range throws ArrayIndexOutOfBoundsException. The check is part of the language, and it cannot be turned off.
  • A data race gives surprising results, but the memory model limits them. A race does not make the meaning of the whole program undefined.

This code has a memory error, on purpose, and the sanitizer reports it.

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

int next(int x) {
    return x + 1; // undefined when x is INT_MAX
}

int main(void) {
    printf("%d\n", next(41));
    printf("%d\n", next(INT_MAX));
}

UndefinedBehaviorSanitizer stops the program at the second call with the report "signed integer overflow". Without the sanitizer, the program has no defined output. Do not trust a value that an unsanitized build prints.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stddef.h>
#include <stdio.h>

struct node {
    int value;
};

int value_or_zero(struct node *n) {
    int v = n->value; // the dereference comes first
    if (n == NULL) {  // so the compiler may remove this check
        return 0;
    }
    return v;
}

int main(void) {
    struct node one = {7};
    printf("%d\n", value_or_zero(&one));
    printf("%d\n", value_or_zero(NULL));
}

The sanitizer reports a member access within a null pointer. The check n == NULL comes after n->value, so an optimizer may delete it. GCC does this by default with -fdelete-null-pointer-checks.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

unsigned int bit(int n) {
    return 1u << n; // undefined when n is 32 or more
}

int main(void) {
    printf("%u\n", bit(3));
    printf("%u\n", bit(32));
}

A shift by the width of the type or more is undefined, also for unsigned types. Hardware differs here, so the standard does not pick one result.

#include <limits.h>
#include <stdckdint.h>
#include <stddef.h>
#include <stdio.h>

struct node {
    int value;
};

int value_or_zero(const struct node *n) {
    if (n == NULL) { // check before the dereference
        return 0;
    }
    return n->value;
}

int main(void) {
    int sum;
    if (ckd_add(&sum, INT_MAX, 1)) {
        printf("INT_MAX + 1 does not fit in int\n");
    }
    printf("value_or_zero(NULL) = %d\n", value_or_zero(NULL));
    unsigned int n = 32;
    printf("1u << %u = %u\n", n, n < 32 ? 1u << n : 0u);
}
Output
INT_MAX + 1 does not fit in int
value_or_zero(NULL) = 0
1u << 32 = 0
#include <stdio.h>

int main(void) {
    printf("sizeof(int) = %zu\n", sizeof(int));
    printf("-7 >> 1 = %d\n", -7 >> 1);
}
Output
sizeof(int) = 4
-7 >> 1 = -4
  • Verdict: native. The C standard defines undefined behavior in 3.5.3 and lists the cases in Annex J.2.
  • ckd_add, ckd_sub and ckd_mul from <stdckdint.h> return true when the result does not fit. The program then never computes the overflowing value.
  • The size of int and the result of -7 >> 1 are implementation-defined. Each implementation documents its choice, and the output above is the choice of the compiler that recorded it.
  • The defined program also runs under -fsanitize=undefined, and the sanitizer reports nothing.
int x = int.MaxValue;
Console.WriteLine(unchecked(x + 1));
try
{
    Console.WriteLine(checked(x + 1));
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);
}

int[] a = [1, 2, 3];
int i = 3;
try
{
    Console.WriteLine(a[i]);
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}
Output
-2147483648
Arithmetic operation resulted in an overflow.
Index was outside the bounds of the array.

This code does not compile, on purpose.

int x = 5;
unsafe
{
    int* p = &x;
    Console.WriteLine(*p);
}

The project does not allow unsafe code, so the compiler rejects the unsafe block with error CS0227.

#:property AllowUnsafeBlocks=true

int x = 5;
unsafe
{
    int* p = &x;
    Console.WriteLine(*p);
}
Output
5
  • Verdict: native. Safe C# gives a defined result or an exception for each operation. The C# specification uses the words "undefined behavior" for unsafe code, for example for the dereference of an invalid pointer.
  • Integer arithmetic is unchecked by default and wraps. checked turns overflow into an OverflowException.
  • Unsafe code needs the unsafe keyword and the AllowUnsafeBlocks project property. The file-based app sets the property with the #:property directive.
JavaScriptGitHub
const x = 2 ** 31 - 1;
console.log(x + 1);
console.log((x + 1) | 0);
console.log([1, 2, 3][3]);
console.log([10, 9, 1].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
Output
2147483648
-2147483648
undefined
[ 1, 10, 9 ]
[ 1, 9, 10 ]

This code runs but gives a wrong answer on purpose.

console.log([3, 1, 2].sort((a, b) => a > b));
Output
[ 3, 1, 2 ]

The comparator returns a boolean, never a negative number. It is not a consistent comparator, so the sort order is implementation-defined. A different engine can give a different order. The result above is the order that Node.js gave.

  • Verdict: absent. ECMAScript gives each operation a defined result. A number is a 64-bit float, so x + 1 does not wrap, and | 0 converts to a 32-bit integer with a defined wrap.
  • A read past the end of an array gives undefined. It does not read other memory.
  • The specification still has implementation-defined parts. The order of sort with an inconsistent comparator is one of them.
  • sort() without a comparator compares the values as strings, so 10 comes before 9.
TypeScriptGitHub
const scores: number[] = [3, 1, 2];
const sorted = [...scores].sort((a, b) => a - b);
console.log(sorted);

const fourth: number | undefined = scores[3];
console.log(fourth ?? "no fourth score");
Output
[ 1, 2, 3 ]
no fourth score
  • Verdict: absent. TypeScript compiles to JavaScript and has the same run-time rules.
  • The type checker rejects the boolean comparator of the JavaScript example with error TS2345, because the comparator must return a number. The runner of this page strips the types without a check, so the page cannot show the error as a fails block.
  • By default, the type of scores[3] is number, but the value is undefined. The compiler option noUncheckedIndexedAccess adds undefined to the type of an index access.
package main

import (
	"fmt"
	"math"
)

func main() {
	x := int32(math.MaxInt32)
	fmt.Println(x + 1)
	fmt.Println(x < x+1)

	s := []int{1, 2, 3}
	i := 3
	defer func() {
		fmt.Println("recovered:", recover())
	}()
	fmt.Println(s[i])
}
Output
-2147483648
false
recovered: runtime error: index out of range [3] with length 3
  • Verdict: absent. The Go specification defines signed overflow: the value wraps, and there is no panic. A compiler may not assume that x < x+1 is always true.
  • An index out of range causes a run-time panic, which recover can stop.
  • Two exceptions remain. Package unsafe allows operations that violate the type system. A data race on a value of more than one machine word, such as a slice or an interface, can corrupt memory.
  • go build -race and go test -race find data races while the program runs.
RustGitHub

This code panics, on purpose.

use std::hint::black_box;

fn main() {
    let x: i32 = black_box(i32::MAX);
    println!("{}", x + 1);
}

Integer overflow is not undefined behavior in Rust. In a debug build, as here, the addition panics with "attempt to add with overflow". In a release build without overflow checks, it wraps. black_box hides the value from the compiler, so that the compiler does not reject the constant overflow at compile time.

fn main() {
    let x = i32::MAX;
    println!("{:?}", x.checked_add(1));
    println!("{}", x.wrapping_add(1));
    println!("{}", x.saturating_add(1));
    println!("{:?}", x.overflowing_add(1));
    let v = vec![1, 2, 3];
    println!("{:?}", v.get(3));
}
Output
None
-2147483648
2147483647
(-2147483648, true)
None

This code does not compile, on purpose.

fn main() {
    let x = 5;
    let p = &raw const x;
    println!("{}", *p);
}

Dereferencing a raw pointer is an unsafe operation. Outside an unsafe block, the compiler rejects it with error E0133.

fn main() {
    let x = 5;
    let p = &raw const x;
    // SAFETY: p points to x, which is alive and initialized here.
    let y = unsafe { *p };
    println!("{y}");
}
Output
5
  • Verdict: native. Undefined behavior exists in Rust, but only code in an unsafe block or an unsafe fn can cause it.
  • In safe code, overflow panics or wraps, an index out of range panics, and get returns None. None of these is undefined behavior.
  • The unsafe keyword does not turn off the checks of safe code. It allows a short list of extra operations, such as the dereference of a raw pointer, and the programmer must make sure that each use is valid.
  • A // SAFETY: comment that says why the operation is valid is the usual style for each unsafe block.
  • Defined errors. Some languages define a bad operation as an error with a known effect, such as a panic or an exception. Safe Rust, Go, Java and C# do this for an index out of range. The cost is a range check on each access.8
  • Wrapping as a choice. Rust, C# and Go make wrapping a defined result. GCC and Clang offer -fwrapv, which makes signed overflow wrap in two's complement for addition, subtraction and multiplication.10 The flag removes this one source of undefined behavior and the optimizations that depend on it.
  • Checked arithmetic in the library. C23 adds ckd_add, ckd_sub and ckd_mul. They compute the result as if the type had infinite range, store the wrapped value, and return true if the stored value is not the true result.17 Rust has checked_add, wrapping_add, saturating_add and overflowing_add. Java has Math.addExact.
  • Undefined behavior on purpose. C23 unreachable() and the C++23 attribute [[assume(expr)]] give the compiler a fact that it can use. If the fact is false at run time, the behavior is undefined.3031 These tools make the optimizer's assumption explicit and local.
  • Weaknesses. Integer overflow or wraparound, NULL pointer dereference, Use after free and Out-of-bounds write describe the security side of the same rules. Data race describes the concurrency side.

Pitfalls

Checking for overflow after the overflow

A test such as if (a + b < a) for signed a and b reads a value that the program had no right to compute. The compiler may fold it to false. The C++ example shows the same error in the form x + 1 > x. Test the operands before the operation, or use ckd_add in C23. Unsigned types wrap by definition, so the test a + b < a is correct for them.

Trusting the output of a debug build

A program with undefined behavior often gives the expected result at -O0 and a different one at -O2. Both builds are correct translations. The C standard requires nothing, and C++ removes every requirement on the whole execution.4 A passing test at one optimization level does not show that the code is correct. Run the tests under -fsanitize=undefined and -fsanitize=address as well.

Shift amounts from data

A shift amount that comes from input can be equal to the width of the type. The result is undefined, also for unsigned types.7 Check the amount first, as the defined C example does: n < 32 ? 1u << n : 0u.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

unsigned int mask(unsigned int bits) {
    return (1u << bits) - 1; // undefined when bits is 32
}

int main(void) {
    printf("%u\n", mask(8));
    printf("%u\n", mask(32));
}

Treating implementation-defined as undefined, or the reverse

-7 >> 1 is implementation-defined in C, so a program may use it on the compilers that document an arithmetic shift.37 -7 << 1 looks like the same kind of operation, but it is undefined, because C defines a left shift of a signed value only when the value is not negative and the result fits.7 Read the clause, or the Annex J entry, before you decide which one you have.

Believing that unsafe code is local

In Rust and C#, undefined behavior in an unsafe block does not stay in the block. If the block breaks an invariant, such as the length of a vector, safe code that runs later can read out of bounds. In Rust, the unsafe code must be correct for every use that safe code can make of it.18

Cost

  • Of undefined behavior. It allows faster code. Lattner gives the examples: no range check on each array access, no extra and for each variable shift, loops that the compiler can analyze, and type-based alias analysis.8 The price is that a small bug can have effects far from its source, and that the effects can change with the compiler version.
  • Of defined behavior. A bounds check adds a compare and a branch to each access. Lattner adds that range checks in C would also need a change of the ABI, so that range information travels with each pointer. Defined wrapping costs the loop optimizations that need the assumption of no overflow.8
  • Of detection. AddressSanitizer slows a program by about 2x.15 UndefinedBehaviorSanitizer adds a check at each instrumented operation. Both are for test builds. The minimal UBSan runtime is the documented exception for production.14

History

  • 1989. The draft of the ANSI C standard (X3.159-1989) defined undefined behavior, unspecified behavior and implementation-defined behavior. Its example of undefined behavior was integer overflow.32
  • 2003. The C99 Rationale explained the three terms: undefined behavior lets an implementation skip errors that are difficult to diagnose, and it marks places where an implementation may extend the language.6
  • 2009. An exploit of the Linux TUN driver used a null check that GCC had removed after a dereference.12
  • 2011. Chris Lattner published a series on the LLVM blog that explained which optimizations depend on undefined behavior and why a small error can have large effects.811
  • 2013 and 2014. GCC 4.8.0 (March 22, 2013) added AddressSanitizer, and GCC 4.9.0 (April 22, 2014) added UndefinedBehaviorSanitizer.333435
  • 2024. C23, the fifth edition of the C standard, added the unreachable macro, whose invocation is undefined if the program reaches it. The same edition has the checked integer macros of <stdckdint.h>.3017

References

  1. N3220, working draft of ISO/IEC 9899:2024 (C23), 3.5.3 undefined behavior, notes 1 and 3 and the example
  2. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 3.65 [defns.undefined] and its note
  3. N3220, working draft of ISO/IEC 9899:2024 (C23), 3.5.1 implementation-defined behavior; 3.5.4 unspecified behavior; Annex J
  4. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 3.26 [defns.impl.defined]; 3.66 [defns.unspecified]; 4.1.2 [intro.abstract], paragraphs 1 to 5 and footnote 6
  5. N3220, working draft of ISO/IEC 9899:2024 (C23), 4 Conformance, paragraphs 2 and 5
  6. Rationale for International Standard, Programming Languages, C, Revision 5.10, April 2003, 3 Terms, definitions, and symbols, page 11
  7. N3220, working draft of ISO/IEC 9899:2024 (C23), 6.5.1 General, paragraphs 2 and 5; 6.5.4.2 Address and indirection operators, paragraph 4 and footnote 101; 6.5.8 Bitwise shift operators, paragraphs 3 to 5
  8. Chris Lattner, What Every C Programmer Should Know About Undefined Behavior, Signed integer overflow; Oversized Shift Amounts; Dereferencing a NULL Pointer; Violating Type Rules
  9. Using the GNU Compiler Collection, Options That Control Optimization, -fdelete-null-pointer-checks; -fstrict-aliasing
  10. Using the GNU Compiler Collection, Options for Code Generation Conventions, -fwrapv
  11. Chris Lattner, What Every C Programmer Should Know About Undefined Behavior, the contains_null_check example (Dead Code Elimination and Redundant Null Check Elimination)
  12. Jonathan Corbet, Fun with NULL pointers, part 1, LWN.net, July 20, 2009, the tun_chr_poll() code and the paragraph on the NULL test that GCC removes
  13. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 6.9.2.3 [intro.progress], paragraph 1 and note 1
  14. Clang documentation, UndefinedBehaviorSanitizer, Introduction; Available checks; Issue suppression and the -fno-sanitize-recover option; Minimal runtime
  15. Clang documentation, AddressSanitizer, Introduction (the list of bugs and the typical slowdown); Security Considerations
  16. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 7.7 [expr.const], paragraph 5.8
  17. N3220, working draft of ISO/IEC 9899:2024 (C23), 7.20 Checked Integer Arithmetic <stdckdint.h>, 7.20.1 paragraphs 2 and 5
  18. The Rust Reference, Behavior considered undefined, [undefined.intro] and the list that follows
  19. The Rust Reference, Behavior not considered unsafe, Integer overflow
  20. The Rust Reference, Unsafety, [safety.unsafe-ops]
  21. The Rustonomicon, Meet Safe and Unsafe, the paragraph that begins "Safe Rust is the true Rust programming language"
  22. The Go Programming Language Specification, Integer overflow; Package unsafe
  23. The Go Memory Model, Introduction (the paragraph on implementation constraints); Implementation Restrictions for Programs Containing Data Races
  24. The Java Language Specification, Java SE 25 Edition, 15.18.2 Additive Operators (+ and -) for Numeric Types
  25. The Java Language Specification, Java SE 25 Edition, 17.4.5 Happens-before Order (the paragraph on operations not affected by data races)
  26. C# language specification, Unsafe code, 24.6.2 Pointer indirection; 24.6.4 Pointer element access
  27. C# language reference, The checked and unchecked statements, the first paragraph
  28. ECMA-262, ECMAScript 2026 Language Specification, 23.1.3.30.1 SortIndexedProperties, the paragraph on the sort order
  29. The Python Language Reference, Data model, Python 3.14, 3.2.4.1 numbers.Integral, Integers (int)
  30. N3220, working draft of ISO/IEC 9899:2024 (C23), 7.21.1 The unreachable macro; M.2 Fifth Edition
  31. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 9.12.3 [dcl.attr.assume]
  32. Draft of ANSI X3.159-1989, Programming Language C, 1.6 Definitions of terms, and its Examples
  33. GCC 4.8 Release Series, Changes, New Features, and Fixes, General Optimizer Improvements, AddressSanitizer
  34. GCC 4.9 Release Series, Changes, New Features, and Fixes, General Optimizer Improvements, UndefinedBehaviorSanitizer
  35. GCC Releases, the release dates of GCC 4.8.0 and GCC 4.9.0
  36. The Python Standard Library, ctypes, Python 3.14, the introduction (the warning on incorrect use); Calling functions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CJ0J7P/text.yaml