Code that violates the C++ standard, allowing the compiler to do anything.
Undefined behavior (UB) means the C++ standard places no requirements on what the program must do. The compiler is free to assume UB never happens and optimize based on that assumption, which can cause the program to produce wrong results, crash, or silently produce different output on different platforms or compilers.
Common UB triggers: signed integer overflow, reading uninitialized variables, out-of-bounds array access, dereferencing null pointers, use-after-free, violating strict aliasing rules, and shifting by a negative amount or by more than the type width.
1#include <iostream>2 3int main() {4 // Undefined behavior 1: uninitialized variable read5 int x;6 std::cout << x << std::endl; // Could print anything!7 8 // Undefined behavior 2: signed integer overflow9 int maxVal = INT_MAX;10 int overflow = maxVal + 1; // UB — can produce negative or crash11 std::cout << overflow << std::endl;12 13 // Undefined behavior 3: out-of-bounds array access14 int arr[5];15 arr[10] = 42; // Writing to memory you don't own16 17 return 0;18}1#include <iostream>2#include <climits>3#include <cstdint>4 5int main() {6 // Fix 1: Always initialize variables7 int x = 0;8 std::cout << x << std::endl; // Guaranteed: 09 10 // Fix 2: Use unsigned types or check before overflow11 unsigned int uMax = UINT_MAX;12 unsigned int noOverflow = uMax + 1; // Wraps to 0 — well-defined for unsigned13 std::cout << noOverflow << std::endl; // 014 15 // For signed: check before adding16 int maxVal = INT_MAX;17 if (maxVal < INT_MAX) { // Only add if it won't overflow18 int safe = maxVal + 1;19 }20 21 // Fix 3: Use bounds-checked containers22 std::array<int, 5> arr{}; // Zero-initialized23 // arr.at(10) = 42; // Throws std::out_of_range instead of UB24 if (10 < arr.size()) {25 arr[10] = 42;26 }27 28 return 0;29}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Each line demonstrates undefined behavior the compiler is technically permitted to exploit. An optimizing compiler might remove code it proves can only execute through UB, miscompile it in surprising ways, or silently produce the 'right' answer in debug builds but the wrong answer in release builds. UB is especially dangerous because it often appears to 'work' until it doesn't.