Skip to content
LeetQuant
E12 Advanced C++

E12 · Advanced C++ · Lesson 5 of 5

Undefined Behaviour

What undefined behaviour means to an optimiser, demonstrated with real -O2 programs (an overflow check deleted, an out-of-bounds loop turned into return true, a never-called function called), plus strict aliasing, uninitialised reads, lifetime bugs, data races and the tools that catch them.

20 min

"No requirements", taken literally

The standard sorts behaviour into four kinds:

KindMeaningExample
well definedone resultunsigned overflow wraps modulo 2n2^{n}
implementation-definedthe implementation chooses and documentssizeof(long), whether char is signed
unspecifiedone of several results, undocumentedorder of evaluation of function arguments
undefinedthe standard imposes no requirements on the whole programsigned overflow, out-of-bounds access, data races

Intuition: the compiler does not "detect UB and do something weird". It assumes UB never happens and optimises the program that remains. Each assumption ("this int addition does not overflow", "this pointer is not null because it was dereferenced", "an int* and a float* point to different objects") is individually reasonable and enables real speedups, such as using 64-bit induction variables in loops indexed by int. Combined with your bug, they produce code that does what nobody wrote. And because there are no requirements on the whole execution, the effects can appear before the faulty line runs.

Every program here was compiled with Apple clang 17 on arm64. Outputs are real but, by definition, not guaranteed: another compiler or version may differ.

Exhibit 1: an overflow check and a lookup, at -O0 and -O2

#include <climits>
#include <cstdio>
#include <cstdlib>

__attribute__((noinline)) bool will_overflow(int x) { return x + 1 < x; }   // "overflow check"

__attribute__((noinline)) bool in_table(int v) {
    static const int table[4] = {1, 2, 3, 4};
    for (int i = 0; i <= 4; ++i)          // off by one: reads table[4]
        if (table[i] == v) return true;
    return false;
}

int main(int argc, char** argv) {
    int x = argc > 1 ? std::atoi(argv[1]) : INT_MAX;
    std::printf("will_overflow(%d) = %d\n", x, will_overflow(x));
    std::printf("in_table(42) = %d\n", in_table(42));
}
$ c++ -std=c++20 -O0 -Wall ub1.cpp && ./a.out
will_overflow(2147483647) = 1
in_table(42) = 0
$ c++ -std=c++20 -O2 -Wall ub1.cpp && ./a.out
will_overflow(2147483647) = 0
in_table(42) = 1

Both answers flip between optimisation levels. The -O2 assembly:

will_overflow(int):        in_table(int):
    mov  w0, #0                mov  w0, #1
    ret                        ret
  • will_overflow. Signed overflow is UB, so for every valid execution x+1>xx + 1 > x holds, and x + 1 < x is false. The compiler returns 0 without looking at x. At -O0 the hardware add wraps to INT_MIN and the check "works", which is how this bug passes debug-build testing.
  • in_table. The loop reads table[4] on its last iteration, which is UB. So any valid execution must leave the loop through return true within the first four iterations. Hence the function always returns true, even for 42, which is not in the table.

-fwrapv (define signed overflow as wrapping) makes will_overflow(INT_MAX) return 1 again, but in_table(42) still returns 1: there is no flag that makes out-of-bounds reads defined.

Exhibit 2: calling a function nobody calls

#include <cstdio>

static void (*handler)() = nullptr;

static void cancel_all_orders() { std::puts("cancel_all_orders() called!"); }
void install_kill_switch() { handler = cancel_all_orders; }   // never called

int main() {
    handler();     // calls a null pointer: UB
}
$ c++ -std=c++20 -O0 -Wall ub2.cpp && ./a.out; echo "exit $?"
exit 139
$ c++ -std=c++20 -O2 -Wall ub2.cpp && ./a.out; echo "exit $?"
cancel_all_orders() called!
exit 0

At -O0, calling a null pointer crashes (139 = 128 + SIGSEGV). At -O2, Clang reasons: handler is static, so only this file can store to it; the only values ever stored are nullptr and cancel_all_orders; calling nullptr is UB; so at the call it must be cancel_all_orders. It calls it directly. A crash became a kill switch firing.

Strict aliasing

The aliasing rule: an object may be accessed only through an lvalue of its own type (ignoring const and signedness), or through char, unsigned char or std::byte. So the compiler may assume an int* and a float* never point to the same memory.

#include <cstdio>

__attribute__((noinline)) int store_and_read(int* i, float* f) {
    *i = 1;
    *f = 0.0f;     // the compiler assumes an int and a float never share memory
    return *i;     // so this is folded to "return 1"
}

int main() {
    int x = 0;
    int r = store_and_read(&x, reinterpret_cast<float*>(&x));   // UB: float lvalue for an int object
    std::printf("returned %d, x is now %d\n", r, x);
}
-O0:                         returned 0, x is now 0
-O2:                         returned 1, x is now 0
-O2 -fno-strict-aliasing:    returned 0, x is now 0

The -O2 code stores 1, stores 0 through the other pointer, then returns the constant 1 without reloading (mov w0, #1). Memory says 0; the function says 1. The fix is not the flag but correct code: copy bytes with std::memcpy or std::bit_cast<std::uint32_t>(f), which compilers turn into a single register move. The same rule makes *reinterpret_cast<const int32_t*>(buffer + 3) on a network buffer UB (it is also misaligned): decode with memcpy.

Uninitialised reads, lifetime and data races

Uninitialised reads.

#include <cstdio>

__attribute__((noinline)) int side_sign(bool is_buy) {
    int sign;                 // forgot the sell branch's assignment
    if (is_buy) sign = +1;
    return sign;
}

int main(int argc, char**) {
    std::printf("buy %d, sell %d\n", side_sign(true), side_sign(argc > 5));
}

Clang warns (-Wsometimes-uninitialized: "variable 'sign' is used uninitialized whenever 'if' condition is false"), and at -O2 compiles side_sign to mov w0, #1; ret: since reading sign on the false path is UB, it may as well be 1. Both calls print 1, so every sell is booked as a buy. With -ftrivial-auto-var-init=zero the run printed buy 1, sell 0: a mitigation that makes the bug deterministic, not a fix.

Lifetime.

#include <cstdio>
#include <string>
#include <string_view>
#include <vector>

std::string make_sym() { return "BRK.B-CLASS-SHARES-LONG-NAME"; }

int main() {
    std::string_view sv = make_sym();        // the temporary string dies at the end of this line
    std::printf("view: %.*s\n", int(sv.size()), sv.data());

    std::vector<int> qty = {100};
    int& first = qty[0];
    qty.push_back(200);                       // may reallocate: 'first' now dangles
    std::printf("first = %d\n", first);
}
life.cpp:9:27: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
$ ./life
view:
first = 3

The string_view points into a destroyed temporary (our run printed an empty string); push_back reallocated and first refers to freed memory (our run printed 3, not 100). Clang caught the first at compile time and not the second. Neither result is reproducible.

Data races. Two threads increment a plain long a million times each:

#include <cstdio>
#include <thread>
long fills = 0;                               // shared, not atomic, no lock
int main() {
    auto work = [] { for (int i = 0; i < 1'000'000; ++i) ++fills; };
    std::thread a(work), b(work);
    a.join(); b.join();
    std::printf("fills = %ld (expected 2000000)\n", fills);
}

At -O0, five runs printed 1099964, 1111808, 1057247, 1095665 and 1077600: lost updates, as expected. At -O2 three runs printed exactly 2000000, because the compiler, entitled to assume no other thread touches fills, replaced each thread's loop with one load, one add of 1,000,000 (add x9, x9, #244, lsl #12 then add x9, x9, #576, i.e. 244×4096+576=106244 \times 4096 + 576 = 10^{6}) and one store. The race is still there; it now loses a whole thread's work only when the two load-add-store sequences overlap. "It passes at -O2" proves nothing. Use std::atomic<long> with fetch_add, or better, per-thread counters summed after join.

Tools that catch UB

ToolFlagCatchesCost
UBSan-fsanitize=undefinedsigned overflow, bad shifts, out-of-bounds on arrays of known size, misaligned access, null dereference, invalid enum/bool loadssmall; usable in CI and often in tests
ASan-fsanitize=addressheap/stack/global buffer overflows, use after free, use after return, double free, leaks (on Linux)about 2x slower, much more memory
TSan-fsanitize=threaddata races, with both racing stacks5 to 15x slower; cannot combine with ASan
libc++ hardening-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FASTvector::operator[] and similar out of range, in optimised buildsa few checks; cheap enough for some production builds
Warnings-Wall -Wextrauninitialised variables, some dangling referencesfree

UBSan on a program with four bugs (-O1 -g -fsanitize=undefined, run with n = 4):

#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>

int main(int argc, char** argv) {
    int n = argc > 1 ? std::atoi(argv[1]) : 4;   // run-time values so nothing folds away

    int qty = INT_MAX - 1 + (n - 3);
    std::printf("qty+1 = %d\n", qty + 1);           // signed overflow

    int shift = 28 + n;
    std::printf("1<<shift = %d\n", 1 << shift);     // shift >= width of int

    int levels[4] = {10, 20, 30, 40};
    std::printf("levels[n] = %d\n", levels[n]);     // index 4 is out of bounds

    alignas(8) unsigned char buf[16] = {};
    long* p = reinterpret_cast<long*>(buf + n - 3); // misaligned long*
    std::printf("*p = %ld\n", *p);
}
ubsan.cpp:10:37: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
ubsan.cpp:13:38: runtime error: shift exponent 32 is too large for 32-bit type 'int'
ubsan.cpp:16:37: runtime error: index 4 out of bounds for type 'int[4]'
ubsan.cpp:20:31: runtime error: load of misaligned address 0x00016b3f2a41 for type 'long', which requires 8 byte alignment

(The SUMMARY lines and memory dump are omitted.) The program kept running and printed 1<<shift = 1 (arm64 shifts use the exponent modulo 32) and levels[n] = -16: garbage that a test would not have flagged. UBSan also catches Exhibit 1: run on ub1.cpp, it reported the overflow at line 5 and "index 4 out of bounds for type 'const int[4]'" at line 10.

For std::vector, UBSan cannot see the bounds; libc++ hardening can. Reading levels[4] of a four-element vector printed 3 in a normal -O2 build and trapped (exit status 133, SIGTRAP) with hardening on.

ASan and TSan are the standard tools for the lifetime and race bugs above. Run them in CI on the test suite, separately (they cannot be combined), and treat any report as a bug.

Worked example

interview question, why does my overflow check not work?

"This guard is meant to reject an order whose quantity would overflow when we add a fill. It passes the unit test in a debug build and never fires in production. Why, and how do you fix it?"

bool would_overflow(int qty, int fill) { return qty + fill < qty; }
Show solution

Say it in three steps.

  1. Diagnosis. Signed overflow is UB, so the compiler may assume qty + fill is the mathematical sum. For fill >= 0 the condition is then false, so the check reduces to fill < 0, which is never true for a fill. Exactly like will_overflow, which Clang compiled to return 0 at -O2. The debug build "worked" because it emitted a wrapping hardware add.
  2. Fix: test before you add, using only values that cannot overflow. For fill >= 0: return qty > INT_MAX - fill;. In general use the compiler builtin __builtin_add_overflow(qty, fill, &out) (GCC and Clang), which returns true on overflow and compiles to an add plus a flag check; C++26 adds std::add_sat and friends. Our test program confirmed __builtin_add_overflow(INT_MAX, 1, &r) reports overflow at -O2. Or widen: do the arithmetic in std::int64_t and range-check the result.
  3. Prevention. Add a UBSan build to CI; it reports "signed integer overflow: 2147483647 + 1" at the exact line. Use fixed-width, wide enough types for quantities and notionals: 50'000 * 100'000 in int is already UB.

Worked example

spot the UB in a message decoder

Find the undefined behaviour in each function, then fix it.

#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>

std::int32_t parse_qty(const unsigned char* msg) {
    return *reinterpret_cast<const std::int32_t*>(msg + 3);       // (1)
}
int notional(int px_ticks, int qty) { return px_ticks * qty; }     // (2)
int distance(int a, int b) { return std::abs(a - b); }             // (3)
std::uint64_t bit(int k) { return 1 << k; }                         // (4)

int main(int argc, char**) {
    alignas(4) unsigned char msg[16] = {0, 0, 0, 100, 0, 0, 0};
    std::printf("%d\n", parse_qty(msg));
    std::printf("%d\n", notional(50'000 * argc, 100'000));
    std::printf("%d\n", distance(INT_MIN + argc - 1, 0));
    std::printf("%llu\n", (unsigned long long)bit(39 + argc));
}
Show solution
  1. parse_qty: reads 4 bytes at msg + 3 through an int32_t*. That violates strict aliasing (the bytes are unsigned char objects) and alignment (address 3 mod 4). Fix: std::int32_t q; std::memcpy(&q, msg + 3, sizeof q); return q;.
  2. notional: 50,000×100,000=5×10950{,}000 \times 100{,}000 = 5 \times 10^{9} exceeds 231−1≈2.147×1092^{31} - 1 \approx 2.147 \times 10^{9}. Fix: compute in std::int64_t.
  3. distance: std::abs(INT_MIN) cannot be represented (and a - b can overflow for other inputs). Fix: widen to 64 bits before subtracting.
  4. bit: 1 is an int, so 1 << 40 shifts a 32-bit value by more than its width. Converting to uint64_t afterwards is too late. Fix: std::uint64_t{1} << k, with k < 64.

UBSan flagged all four (-O1 -g -fsanitize=undefined):

spot.cpp:8:12: runtime error: load of misaligned address 0x00016d362a63 for type 'const std::int32_t' (aka 'const int'), which requires 4 byte alignment
spot.cpp:10:55: runtime error: signed integer overflow: 50000 * 100000 cannot be represented in type 'int'
spot.cpp:11:48: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself
spot.cpp:12:37: runtime error: shift exponent 40 is too large for 32-bit type 'int'

The program still printed plausible-looking numbers: 100, 705032704 (which is 5×109−2325 \times 10^{9} - 2^{32}), -2147483648 and 256. Note what UBSan did not report: the aliasing violation. UBSan checks alignment, not type-based aliasing, so code review and memcpy discipline are still needed.

Knowledge check

Why did Clang compile bool will_overflow(int x) { return x + 1 < x; } to return false at -O2?

Knowledge check

A function writes i = 1 through an int, then f = 0.0f through a float that actually points to the same int, then returns *i. At -O2 it returned 1 while memory held 0. What is the correct fix?

Knowledge check

Two threads increment a plain global long a million times each. At -O2 the total is always exactly 2,000,000. What can you conclude?

Key takeaways

  • UB places no requirements on the whole program; optimisers assume it never happens, and the results can be deletions, constant answers or calls nobody wrote.
  • Signed overflow, out-of-bounds access, null dereference, strict-aliasing violations, uninitialised reads, dangling references and data races are all UB. Unsigned overflow is not.
  • A debug build that "works" is not evidence: every exhibit here behaved differently at -O0 and -O2.
  • Check overflow before the operation (__builtin_add_overflow, or widen); copy bytes with memcpy or std::bit_cast; share mutable data between threads only through atomics or locks.
  • Run UBSan, ASan and TSan in CI and turn on libc++ hardening where you can afford it; UBSan does not check aliasing, so review that by hand.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).