Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Types and Language Concepts

Undefined behavior in C++

Concept page on C++ undefined, unspecified and implementation-defined behavior: common causes, why compilers exploit it, and safe alternatives.

Undefined behavior (UB) means the C++ standard places no requirements on what a program does once it executes a certain operation. The program may crash, print a wrong result, appear to work, or behave differently after you change the optimization level or the compiler version. The important point is that UB is not limited to the line that causes it: because compilers assume UB never happens, they may delete checks and reorder code in ways that make the whole program meaningless.

Two neighboring terms are easy to confuse with it. Unspecified behavior lets the implementation choose among several valid outcomes without documenting the choice (the order in which function arguments are evaluated). Implementation-defined behavior also lets the compiler choose, but it must document the choice (the size of int, the sign of char). Both give a valid result; UB does not.

C++
int a[3] = {1, 2, 3};
int x = a[3];      // undefined: index 3 is one past the end

Try it

C++ Defined alternatives to common UB

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ The compiler catches UB in constant expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The usual suspects

  • Out-of-bounds access to arrays, std::vector::operator[], std::string::operator[] (beyond size()), std::span, and pointer arithmetic that leaves the array (one past the end is allowed to form, not to dereference).
  • Signed integer overflow, including INT_MIN / -1, -INT_MIN and abs(INT_MIN). Unsigned arithmetic wraps and is fine.
  • Shifts by a negative amount or by an amount greater than or equal to the bit width. (Left-shifting a negative value was UB before C++20.)
  • Null and dangling pointers: dereferencing nullptr, using a pointer after delete, returning a reference to a local variable, using an iterator after the container reallocated (see Object lifetime).
  • Uninitialized reads: using a local int before assigning it. Value-initialize (int x{};) to be safe.
  • Data races: two threads access the same non-atomic object and at least one writes (see The memory model).
  • Violating the type system: accessing an object through a pointer of an unrelated type (strict aliasing), reinterpret_cast followed by a read, calling a virtual function from a deleted object, delete on a base pointer without a virtual destructor, mixing new[] with delete.
  • Modifying a const object, modifying a string literal, and modifying a variable twice in one expression without sequencing (i = i++ + ++i is still undefined in C++17 and later, even though i = i++ became defined in C++17).
  • Falling off the end of a non-void function without return (UB in C++; main is exempt).
  • Violated preconditions: std::vector::front() on an empty vector, std::sort with a comparator that is not a strict weak ordering, a division by zero, std::unreachable(), or an infinite loop without side effects (C++26 changes this last rule).
  • ODR violations such as two different definitions of the same inline function (see One Definition Rule).

Usage notes

  • UB is a runtime and compile-time property. If the compiler can prove UB happens while evaluating a constexpr expression, it must reject the program, which is a good way to test code.
  • "It works on my machine" is not evidence. Optimization levels, new compiler versions and unrelated edits can change the result.
  • Use tools: compile tests with -fsanitize=address,undefined (and thread for races), enable -Wall -Wextra, and use -D_GLIBCXX_ASSERTIONS to turn many standard-library preconditions into checked failures.
  • Prefer checked or safe abstractions: at(), std::optional, std::span, range-based for, std::bit_cast, std::in_range, std::unique_ptr, and containers over raw new/delete.
  • Hardened libraries (C++26) make some standard library preconditions diagnosable; the language's own contracts feature is not available on our runner.
  • Unspecified is not undefined, but code that depends on a particular choice is still wrong. Do not rely on argument evaluation order; write separate statements.