In C and C++, a single line of undefined behaviour gives the optimiser permission to delete the very safety check a developer wrote to stop an attack. Undefined behaviour (UB) is any construct for which the language standard imposes no requirements, such as signed integer overflow, a null pointer dereference or an out-of-bounds read. Modern compilers assume UB never happens and optimise on that assumption, so a bug that looks harmless in source can compile into a missing bounds check or a removed null test. This guide explains how that happens, which UB classes most often become vulnerabilities, how to find them with UndefinedBehaviorSanitizer (UBSan), AddressSanitizer (ASan) and static analysis, and which compiler flags and coding rules (SEI CERT, MISRA) take the optimiser's licence away. It is written for C and C++ developers and secure code reviewers. Broader safe coding patterns are in the C and C++ Secure Coding Guide; this page goes deeper on UB itself.
Key takeaways
- UB is a contract, not a crash. The standard says the compiler may assume UB never occurs, so it can remove checks, reorder code and fold conditions to constants in ways that do not match the source.
- Checks written after the bug get deleted. Overflow tests such as
a + 100 > aon signed integers, and null tests placed after a dereference, are the classic cases the optimiser legally removes. - Sanitizers find UB that tests miss. Run UBSan and ASan builds in CI and under fuzzing; the default build will usually hide the problem until an attacker supplies the triggering input.
- Flags can define away whole classes.
-fno-strict-overflow,-fno-delete-null-pointer-checks,-fno-strict-aliasingand-ftrivial-auto-var-init=zeroare recommended by OpenSSF for production code and used by the Linux kernel. - Rules make UB reviewable. SEI CERT C rules and MISRA C:2023 Rule 1.3 give reviewers and analysers a named target, and safer subsets or memory-safe languages shrink the surface over time.
What undefined behaviour is
The C and C++ standards sort non-portable behaviour into distinct buckets, and the difference matters for security review:
| Category | What the standard requires | Example | Security relevance |
|---|---|---|---|
| Implementation-defined | Varies by implementation, which must document its choice | Size of long, number of bits in a byte | Portability bugs; predictable on one platform |
| Unspecified | One of a set of valid results; need not be documented | Order of evaluation of function arguments | Logic errors when code relies on one order |
| Erroneous behaviour (C++26) | Incorrect code the implementation is recommended to diagnose; may terminate | Reading an uninitialised automatic variable | Bounded: removes a classic source of info leaks in C++26 |
| Undefined | No requirements at all, no diagnostic needed | Signed overflow, null dereference, out-of-bounds access, data races, access through an incompatible pointer type | Optimiser may remove checks; the binary can do anything |
The important word is "no requirements". The SEI CERT C recommendation MSC15-C (do not depend on undefined behaviour) notes that because compilers are not obliged to generate code for UB, they can optimise on the assumption that it never occurs, which breaks the cause and effect a reviewer expects when reading source. UB is also not the same as "whatever the hardware does": the fact that x86 integer addition wraps does not make signed overflow wrap in C.
How optimisers use UB
Optimisers reason forward and backward from operations that would be UB. If a path would trigger UB, the compiler may treat that path as impossible, and anything that only matters on that path can be simplified away. The illustrations below are adapted from cppreference and the SEI CERT and OpenSSF material; they are teaching examples, not exploits.
Signed overflow checks folded to true
1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.
int will_fit(int x) {
return x + 1 > x; /* either true, or UB: compiled as "return 1" */
}cppreference shows this compiling to a constant 1. CERT's MSC15-C example uses assert(a + 100 > a) and reports that older GCC releases removed the assertion entirely at -O2. The fix is to test before the operation: if (a > INT_MAX - 100), or use C23 ckd_add() from <stdckdint.h>, which returns true on overflow.
Null checks after a dereference removed
1 Sample only. This step can disrupt services or delete data. It is based on the public documentation cited: assess it independently against the current official documentation, test outside production and back up first. Use at your own risk.
int read_flag(struct dev *d) {
int v = d->flags; /* dereference first */
if (!d) return -1; /* compiler may delete: d "cannot" be null here */
return v;
}This is the pattern behind the 2009 Linux kernel tun driver flaw described by the SANS Internet Storm Center: a pointer was used before its null check, the compiler removed the check, and on systems that allowed mapping memory at address zero a local attacker could turn an otherwise harmless oops into code execution. The OpenSSF guide quotes Linus Torvalds explaining that removing the check "turned a benign bug into a trivially exploitable one", and the kernel now builds with -fno-delete-null-pointer-checks.
Other optimiser behaviours worth knowing
- Out-of-bounds loops: a loop that reads one element past an array can let the compiler assume the loop always returns early, so the function is compiled to return a constant.
- Uninitialised reads: a variable set on only one branch can be treated as always holding that branch's value.
- Strict aliasing: accessing an object through a pointer of an unrelated type lets the compiler cache values in registers and miss writes, which breaks packet parsing and type-punning code.
- Use after
realloc: using the old pointer afterreallocis UB even if the address did not change, and Clang can produce results where two "equal" pointers read different values. - Side-effect-free infinite loops: in C++ these may be assumed to terminate, so code after them can run.
UB classes that become vulnerabilities
Not all UB is equally dangerous. The table maps the classes that most often appear in security fixes to their impact, the tool most likely to catch them, and the SEI CERT C rule a reviewer can cite.
| UB class | Typical security impact | Detection tool | SEI CERT C rule |
|---|---|---|---|
| Signed integer overflow | Removed overflow checks, undersized allocation, then heap overflow | UBSan signed-integer-overflow | INT32-C |
| Out-of-bounds array or pointer access | Memory corruption, information disclosure | ASan; UBSan bounds, object-size | ARR30-C, ARR38-C |
| Null pointer dereference | Denial of service; deleted null checks; kernel privilege escalation where page zero is mappable | UBSan null | EXP34-C |
Use after free, use after realloc | Code execution through heap reuse | ASan | MEM30-C |
| Uninitialised read | Leak of stack or heap secrets; inconsistent checks | MemorySanitizer, Valgrind, compiler warnings | EXP33-C |
| Oversized or negative shift | Wrong masks and bounds calculations | UBSan shift | INT34-C |
Division by zero, INT_MIN / -1 | Crash or trap, denial of service | UBSan integer-divide-by-zero, signed-integer-overflow | INT33-C |
| Incompatible type access (strict aliasing) | Stale values in parsers, skipped validation | Compiler warnings, static analysis | EXP39-C |
Misaligned access, invalid bool or enum | Unexpected branches and crashes | UBSan alignment, bool, enum | EXP36-C |
| Data race | Time-of-check to time-of-use flaws, corrupted state | ThreadSanitizer | CON43-C |
| Wrong dynamic type (C++) | Type confusion, virtual call hijack | UBSan vptr | C++ Core Guidelines type rules |
Unsigned overflow is defined (it wraps), but it still causes undersized allocations. Clang's -fsanitize=integer group adds unsigned overflow and implicit truncation checks that are not UB but often unintended; use them on parsers and size calculations. The Memory Corruption Vulnerabilities Guide explains how the memory classes are abused.
Finding UB: sanitisers and static analysis
UB rarely shows up in normal testing because the default optimised build silently does something plausible. Detection needs instrumented builds and hostile inputs.
| Technique | Flag or tool | Catches | Where to run |
|---|---|---|---|
| UndefinedBehaviorSanitizer | -fsanitize=undefined (GCC 4.9+, Clang 3.3+), needs -O1 or higher for sensible speed | Signed overflow, shifts, null, bounds, alignment, bool/enum loads, vla-bound, missing return | Unit tests, integration tests, fuzzing |
| AddressSanitizer | -fsanitize=address | Heap, stack and global out-of-bounds, use after free, double free | CI and fuzzing (can share a build with UBSan) |
| MemorySanitizer | -fsanitize=memory (Clang) | Reads of uninitialised memory | Separate build; all code must be instrumented |
| ThreadSanitizer | -fsanitize=thread | Data races | Separate build from ASan |
| Coverage-guided fuzzing | libFuzzer, AFL++ with ASan and UBSan | Inputs that reach UB in parsers and decoders | Continuous; OSS-Fuzz for open source |
| Static analysis | Clang Static Analyzer, clang-tidy, GCC -fanalyzer, CERT or MISRA checkers | Null paths, uninitialised use, rule violations on paths tests never execute | Pull requests, diff-based gating |
| Constant evaluation | constexpr unit tests in C++ | UB in code evaluated at compile time is a hard error | Small pure functions such as size arithmetic |
- Make findings fail tests: by default most UBSan checks print a report and continue. Use
-fno-sanitize-recover=undefinedin CI so a finding fails the job, and setUBSAN_OPTIONS=print_stacktrace=1with-gfor usable reports. - Know what the group omits: Clang's
-fsanitize=undefineddoes not includeunsigned-integer-overflow,implicit-conversion,local-boundsor the nullability checks; add them explicitly where they help. - Do not trust a clean run: sanitizers only see executed paths, so pair them with fuzzing and branch coverage targets. The Fuzzing Guide and Fuzzing vs Static Analysis cover the trade-offs.
- Review signals: in code review, treat arithmetic on sizes, any check placed after the operation it guards, pointer casts between unrelated types, and variables initialised on only some branches as UB hotspots.
Compiler flags and hardening
Some flags remove the optimiser's licence for specific UB classes, making behaviour defined and keeping checks in the binary. Others contain the damage when a bug survives. The OpenSSF Compiler Options Hardening Guide for C and C++ lists the first group for production code.
| Flag | Effect on UB | Cost and caveats |
|---|---|---|
-fno-delete-null-pointer-checks | Keeps null checks the compiler could prove "unnecessary" | Normally no significant performance cost; used by the Linux kernel |
-fno-strict-overflow (or -fwrapv) | Signed overflow and pointer arithmetic wrap in two's complement instead of being UB (GCC 8.5+ equates it to -fwrapv -fwrapv-pointer; Clang treats it as -fwrapv) | Fewer loop optimisations; wraps rather than traps, so overflow is now a logic bug to find, not a deleted check |
-ftrapv | Signed overflow traps (for example SIGABRT) | Turns overflow into denial of service; mainly for testing |
-fno-strict-aliasing | Compiler stops assuming different pointer types never alias | Some lost optimisation; used by the Linux kernel |
-ftrivial-auto-var-init=zero (GCC 12+, Clang 8+) | Automatic variables without initialisers start at zero | Overhead in hot paths; masks bugs from MemorySanitizer and Valgrind, so do not use it in instrumented test builds |
-fsanitize=undefined -fsanitize-minimal-runtime (Clang) or -fsanitize-trap=undefined (GCC 13+) | Selected UB checks stay on in production and trap | The only sanitizer configuration OpenSSF describes as suitable for production; measure overhead |
-Werror=return-type, -Wall -Wextra -Wconversion -Wshift-overflow | Compile-time diagnosis of UB-prone constructs | No run-time cost |
Two cautions. First, with link-time optimisation GCC carries -fno-strict-overflow, -fwrapv and -fno-strict-aliasing through to the link stage, where they take precedence over modules built with strict semantics, so performance-tuned modules lose the optimisation. Second, these flags are compiler extensions: code that depends on them is no longer portable C, so they are a safety net, not a licence to write overflowing code. Full ASan builds must never ship to production. Classic run-time hardening (_FORTIFY_SOURCE=3, stack protector, PIE, RELRO, CFI) is covered in the Compiler and Toolchain Hardening Guide and the Exploit Mitigations Guide.
Rolling it out
- Baseline: build each component once with
-fsanitize=undefined,address -fno-sanitize-recover=undefinedand run the full test suite; record findings per component in audit mode, without failing builds. - Fix the parsers first: triage findings in code that handles network, file or IPC input, then make UBSan failures block merges for those components.
- Add the defining flags in a pilot: enable the four OpenSSF production flags on one service, compare benchmarks, and watch crash telemetry in a canary ring.
- Fuzz continuously: attach libFuzzer or AFL++ harnesses with ASan and UBSan to each parser.
- Gate with rules: turn on CERT or MISRA checks in static analysis for new code and track legacy findings down.
- Roll back safely: keep flags in one shared toolchain file so a flag can be disabled per target with a recorded exception and expiry date.
Small teams get most value from a UBSan plus ASan CI job, the four OpenSSF production flags and fuzzing their input parsers. Large organisations should own a central toolchain configuration, report sanitizer coverage per repository and track UB defects found by stage. Safety-critical and embedded teams usually work to MISRA, and may prefer trap-mode UBSan to a runtime library.
Detection and measurement
- Sanitizer coverage: share of C and C++ components with UBSan and ASan CI jobs that fail on findings.
- Fuzz coverage: share of untrusted-input parsers with active fuzz targets.
- UB defects by stage: UB findings per quarter split by static analysis, CI, fuzzing, production and external report; the aim is to move discovery earlier.
- Flag compliance: share of release builds carrying the agreed defining flags, checked from build logs or compiler-recorded options rather than makefiles.
- Rule debt: open CERT or MISRA findings in UB-related rules, trending down.
- Production traps: UBSan trap and minimal-runtime reports from the field, investigated as potential exploitation attempts as well as bugs.
Moving to safer subsets and languages
- MISRA C:2023: Rule 1.3 (Required) states there shall be no occurrence of undefined or critical unspecified behaviour, and many other MISRA rules target specific UB cases. It is the usual baseline in automotive and embedded work and is checkable with commercial analysers.
- SEI CERT C and C++: rules such as INT32-C and EXP34-C, plus the MSC15-C recommendation, are a free, citable standard for code review and analyser configuration. The Secure Coding Standard Template shows how to adopt one.
- Modern language features: C23 checked arithmetic (
ckd_add,ckd_sub,ckd_mul), C++20 and C23 mandating two's complement representation, C++26 erroneous behaviour for uninitialised reads,std::spanand hardened standard library modes all remove or bound specific UB. Beware[[assume]]andstd::unreachable(C++23): they create new UB if the assumption is ever false. - C++ Core Guidelines profiles: the bounds, type and lifetime rules, checked by clang-tidy, cut the most common UB in C++ code.
- Memory-safe languages: for new components that parse untrusted input, choosing Rust, Go, Java, C# or Swift removes most UB classes outright, as CISA and NSA recommend. Unsafe blocks and FFI boundaries carry UB risk back in. See the Memory-Safe Languages Guide.
Framework mapping
| Practice | NIST SP 800-53 Rev. 5 | Other frameworks |
|---|---|---|
| Coding standard covering UB (CERT, MISRA) | SA-15 Development Process, Standards, and Tools; SA-8 | ISO/IEC 27001:2022 Annex A 8.28 Secure coding; CIS Controls v8.1 Control 16 |
| Static analysis for UB rules | SA-11(1) Static Code Analysis | NIST CSF 2.0 PR.PS-06 |
| Sanitizer and fuzz testing | SA-11 Developer Testing and Evaluation | NIST CSF 2.0 PR.PS-06 |
| Defining flags, run-time hardening | SI-16 Memory Protection | Attacks frustrated: MITRE ATT&CK T1190, T1203, T1068 |
Practitioner checklist
- Run a CI build with
-fsanitize=undefined,address -fno-sanitize-recover=undefinedon every C and C++ component. - Add separate MemorySanitizer (Clang) and ThreadSanitizer jobs for code that handles secrets or runs concurrently.
- Fuzz every parser of untrusted input with ASan and UBSan attached.
- Build production code with
-fno-delete-null-pointer-checks -fno-strict-overflow -fno-strict-aliasing -ftrivial-auto-var-init=zero, measured on a pilot first. - Rewrite overflow checks to test before the operation, or use
ckd_*or__builtin_*_overflow. - Move every null check before the first dereference, and flag "check after use" in review.
- Adopt SEI CERT C or MISRA C:2023 and enable the matching static analysis rules for new code.
- Never ship full ASan builds; use only UBSan minimal runtime or trap mode in production.
- Track sanitizer coverage, fuzz coverage and UB defects by stage as metrics.
- Default new untrusted-input components to a memory-safe language.
Standards and references
- OpenSSF: Compiler Options Hardening Guide for C and C++
- LLVM: UndefinedBehaviorSanitizer
- Carnegie Mellon SEI: MSC15-C. Do not depend on undefined behavior
- MathWorks: MISRA C:2023 Rule 1.3
- cppreference: Undefined behavior
- cppreference: ckd_add (C23)
- SANS Internet Storm Center: A new fascinating Linux kernel vulnerability
- CISA and NSA: Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development
Related NHI Mgmt Group resources: C and C++ Secure Coding Guide · Compiler and Toolchain Hardening Guide · Memory-Safe Languages Guide · Fuzzing Guide · Secure Code Review Guide