01 / 21
?!

Undefined Behavior
in C++

Discover why certain C++ code makes no guarantees about what will happen: it might crash, produce wrong results, or appear to work perfectly until it doesn't.

C++

What Is Undefined Behavior?

When the C++ standard says a program has undefined behavior (UB), it means the standard imposes no requirements whatsoever on what the program does. The compiler, the operating system, and the hardware are all free to do absolutely anything.

This is not a bug in the compiler: it is a contract violation by the programmer. You wrote code the language explicitly does not define, so the implementation owes you nothing.

Why Does UB Exist?

Performance
If the compiler can assume certain things never happen (e.g., signed overflow), it can generate faster machine code with aggressive optimizations.
Portability
Different CPUs handle edge cases differently. Leaving behavior undefined lets C++ run efficiently on x86, ARM, RISC-V, and more without mandating one behavior.
Simplicity
Requiring the compiler to detect every possible error at runtime would make programs significantly slower and more complex.

The Nasal Demons Metaphor

Programmers jokingly say UB can make "nasal demons fly out of your nose." The point: once UB occurs, literally anything is a conforming result. There are no constraints on past, present, or future behavior.

UB Triggered at runtime Appears to work Wrong output Crash / segfault Security exploit Any of these. Every time.

The Behavior Spectrum

The C++ standard defines several categories of behavior. Understanding the differences is essential:

Well-Defined Exact result specified by standard Implementation- Defined Compiler picks; must document the choice Unspecified Valid choices exist; compiler needn't document Undefined No requirements. Anything can happen. SAFEST RISKIER DANGER

Implementation-Defined vs Undefined

Implementation-Defined Undefined Behavior
Guaranteed? Yes: consistent result per compiler No: absolutely no guarantees
Documented? Compiler must document its choice No obligation to document anything
Portable? Not across compilers, but predictable Not portable, not predictable
Example \(\text{sizeof}(\text{int})\) Signed integer overflow
Can optimize away? No: must honor its documented behavior Yes: compiler may assume UB never happens

The Core Rule of UB

This is sometimes called the "as-if" rule on steroids. Compilers don't just ignore UB: they exploit it for optimization. A branch that would only be reached via UB can be deleted. A variable that can only hold a certain value if UB happened can be assumed to hold a "safe" value.

Example: optimizer removes a NULL check
void process(int* p) { int x = *p; // dereferences p if (p == nullptr) // compiler: "p was already return; // dereferenced, so it can't use(x); // be null" → removes check! }

Common Sources of UB

1
Signed integer overflow: \(a + b\) wraps for unsigned but is UB for signed types.
2
Null pointer dereference: accessing memory through a null or dangling pointer.
3
Out-of-bounds array access: reading or writing past the end of an array.
4
Use after free: accessing memory that has been deallocated.
5
Uninitialized variables: reading a local variable before assigning it a value.
6
Data races: two threads accessing the same memory without synchronization, and at least one writes.

How to Detect and Avoid UB

1
Enable all warnings: Compile with -Wall -Wextra -Wpedantic. Treat warnings as errors with -Werror.
2
Use sanitizers: Compile with -fsanitize=undefined (UBSan) and -fsanitize=address (ASan) during testing.
3
Initialize all variables: Always assign a value at declaration. Use {} for zero-initialization.
4
Bounds-check arrays: Prefer std::vector::at() or range-based for loops over raw indexing.
5
Validate pointers: Check for null before dereferencing. Use smart pointers (std::unique_ptr, std::shared_ptr).
6
Use static analysis: Tools like clang-tidy and cppcheck catch many UB patterns at compile time.

Example 1: Signed Overflow

UB: signed integer overflow
int x = INT_MAX; // 2,147,483,647 int y = x + 1; // UB! signed overflow
Safe alternative: use unsigned or check first
// Option A: unsigned wraps well-defined unsigned x = UINT_MAX; unsigned y = x + 1; // y == 0, defined behavior // Option B: check before adding if (x < INT_MAX) { y = x + 1; }

Example 2: Out-of-Bounds Access

UB: array index out of range
int arr[5] = {10, 20, 30, 40, 50}; int val = arr[5]; // UB! valid indices are 0-4
10 [0] 20 [1] 30 [2] 40 [3] 50 [4] ?? [5] UB!

Example 3: Use After Free

UB: dangling pointer access
int* p = new int(42); delete p; std::cout << *p; // UB! p is dangling
Step 1: Valid p 42 Step 2: Freed p freed Step 3: UB! *p Dangling! Fix: use std::unique_ptr instead

UB Can Time Travel

One of the most surprising properties of UB is that it can affect code before the undefined operation, not just after it. Because the compiler assumes UB never occurs, it can reason backwards.

UB causes earlier code to be optimized away
bool isValid(int* p) { int dead = *p; // UB if p is null if (p == nullptr) // compiler: "p can't be null return false; // (it was dereferenced)," return true; // so this always returns true }

Uninitialized Variables

UB: reading an uninitialized variable
int x; // uninitialized std::cout << x; // UB! reading indeterminate value
What might happen
Print 0 in debug mode. Print garbage in release. Different result every run. Compiler may assume x has any convenient value and propagate that assumption.
The fix
Always initialize: int x = 0; or use int x{}; for value-initialization. Modern C++ style prefers declaration at point of first use.

Common Mistakes

✕ "It works on my machine"
UB may appear correct in debug mode but fail in release with optimizations. Testing success does not prove absence of UB.
✕ Assuming wrapping for signed int
Unlike unsigned, signed overflow is UB. Code like \(\texttt{if (x + 1 > x)}\) may be optimized to always true by the compiler.
✕ Ignoring compiler warnings
Warnings about uninitialized variables, pointer misuse, and type mismatches often indicate UB. Ignoring them is a ticking time bomb.

UB Quick Reference

Source of UB The Danger The Fix
Signed overflow Compiler removes overflow checks Use unsigned or check first
Null dereference Crash, or null check removed Check before dereferencing
Out-of-bounds Corrupts memory, security holes Use .at() or bounds check
Use after free Reads garbage, security exploit Smart pointers
Uninitialized var Indeterminate value propagates Always initialize
Data race Torn reads, inconsistent state Mutex / atomic

Question 1 of 5

Which of the following is undefined behavior in C++?

Question 2 of 5

A programmer writes code that dereferences a pointer before checking if it is null. What might the compiler do?

Question 3 of 5

What is the key difference between implementation-defined behavior and undefined behavior?

Question 4 of 5

What is wrong with this code?

Question 5 of 5

Which compiler flag enables the Undefined Behavior Sanitizer to detect UB at runtime during testing?