Join our Newsletter — 33% off our NHI Course
Home› Guides› Undefined Behaviour Guide: How C and C++ Compilers…
Guide Application Security

Undefined Behaviour Guide: How C and C++ Compilers Turn Bugs into Vulnerabilities

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 14 min read
On this page

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 > a on 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-aliasing and -ftrivial-auto-var-init=zero are 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:

CategoryWhat the standard requiresExampleSecurity relevance
Implementation-definedVaries by implementation, which must document its choiceSize of long, number of bits in a bytePortability bugs; predictable on one platform
UnspecifiedOne of a set of valid results; need not be documentedOrder of evaluation of function argumentsLogic errors when code relies on one order
Erroneous behaviour (C++26)Incorrect code the implementation is recommended to diagnose; may terminateReading an uninitialised automatic variableBounded: removes a classic source of info leaks in C++26
UndefinedNo requirements at all, no diagnostic neededSigned overflow, null dereference, out-of-bounds access, data races, access through an incompatible pointer typeOptimiser 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.

Sample 1
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.

Sample 1
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 after realloc is 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 classTypical security impactDetection toolSEI CERT C rule
Signed integer overflowRemoved overflow checks, undersized allocation, then heap overflowUBSan signed-integer-overflowINT32-C
Out-of-bounds array or pointer accessMemory corruption, information disclosureASan; UBSan bounds, object-sizeARR30-C, ARR38-C
Null pointer dereferenceDenial of service; deleted null checks; kernel privilege escalation where page zero is mappableUBSan nullEXP34-C
Use after free, use after reallocCode execution through heap reuseASanMEM30-C
Uninitialised readLeak of stack or heap secrets; inconsistent checksMemorySanitizer, Valgrind, compiler warningsEXP33-C
Oversized or negative shiftWrong masks and bounds calculationsUBSan shiftINT34-C
Division by zero, INT_MIN / -1Crash or trap, denial of serviceUBSan integer-divide-by-zero, signed-integer-overflowINT33-C
Incompatible type access (strict aliasing)Stale values in parsers, skipped validationCompiler warnings, static analysisEXP39-C
Misaligned access, invalid bool or enumUnexpected branches and crashesUBSan alignment, bool, enumEXP36-C
Data raceTime-of-check to time-of-use flaws, corrupted stateThreadSanitizerCON43-C
Wrong dynamic type (C++)Type confusion, virtual call hijackUBSan vptrC++ 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.

TechniqueFlag or toolCatchesWhere to run
UndefinedBehaviorSanitizer-fsanitize=undefined (GCC 4.9+, Clang 3.3+), needs -O1 or higher for sensible speedSigned overflow, shifts, null, bounds, alignment, bool/enum loads, vla-bound, missing returnUnit tests, integration tests, fuzzing
AddressSanitizer-fsanitize=addressHeap, stack and global out-of-bounds, use after free, double freeCI and fuzzing (can share a build with UBSan)
MemorySanitizer-fsanitize=memory (Clang)Reads of uninitialised memorySeparate build; all code must be instrumented
ThreadSanitizer-fsanitize=threadData racesSeparate build from ASan
Coverage-guided fuzzinglibFuzzer, AFL++ with ASan and UBSanInputs that reach UB in parsers and decodersContinuous; OSS-Fuzz for open source
Static analysisClang Static Analyzer, clang-tidy, GCC -fanalyzer, CERT or MISRA checkersNull paths, uninitialised use, rule violations on paths tests never executePull requests, diff-based gating
Constant evaluationconstexpr unit tests in C++UB in code evaluated at compile time is a hard errorSmall pure functions such as size arithmetic
  • Make findings fail tests: by default most UBSan checks print a report and continue. Use -fno-sanitize-recover=undefined in CI so a finding fails the job, and set UBSAN_OPTIONS=print_stacktrace=1 with -g for usable reports.
  • Know what the group omits: Clang's -fsanitize=undefined does not include unsigned-integer-overflow, implicit-conversion, local-bounds or 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.

FlagEffect on UBCost and caveats
-fno-delete-null-pointer-checksKeeps 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
-ftrapvSigned overflow traps (for example SIGABRT)Turns overflow into denial of service; mainly for testing
-fno-strict-aliasingCompiler stops assuming different pointer types never aliasSome lost optimisation; used by the Linux kernel
-ftrivial-auto-var-init=zero (GCC 12+, Clang 8+)Automatic variables without initialisers start at zeroOverhead 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 trapThe only sanitizer configuration OpenSSF describes as suitable for production; measure overhead
-Werror=return-type, -Wall -Wextra -Wconversion -Wshift-overflowCompile-time diagnosis of UB-prone constructsNo 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

  1. Baseline: build each component once with -fsanitize=undefined,address -fno-sanitize-recover=undefined and run the full test suite; record findings per component in audit mode, without failing builds.
  2. Fix the parsers first: triage findings in code that handles network, file or IPC input, then make UBSan failures block merges for those components.
  3. 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.
  4. Fuzz continuously: attach libFuzzer or AFL++ harnesses with ASan and UBSan to each parser.
  5. Gate with rules: turn on CERT or MISRA checks in static analysis for new code and track legacy findings down.
  6. 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::span and hardened standard library modes all remove or bound specific UB. Beware [[assume]] and std::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

PracticeNIST SP 800-53 Rev. 5Other frameworks
Coding standard covering UB (CERT, MISRA)SA-15 Development Process, Standards, and Tools; SA-8ISO/IEC 27001:2022 Annex A 8.28 Secure coding; CIS Controls v8.1 Control 16
Static analysis for UB rulesSA-11(1) Static Code AnalysisNIST CSF 2.0 PR.PS-06
Sanitizer and fuzz testingSA-11 Developer Testing and EvaluationNIST CSF 2.0 PR.PS-06
Defining flags, run-time hardeningSI-16 Memory ProtectionAttacks frustrated: MITRE ATT&CK T1190, T1203, T1068

Practitioner checklist

  • Run a CI build with -fsanitize=undefined,address -fno-sanitize-recover=undefined on 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

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.