ub-checks-per-statement · part 04

Which checking tool catches which undefined behavior

· english· audience: working-cpp· AI-generated, reviewed by Filip Sajdak
std::vector<int> v{10, 20, 30};
v[3];                 // index one past the end
INT_MAX + 1;          // signed overflow
10 / 0;               // integer division by zero
*static_cast<int*>(nullptr);   // null dereference
int u; std::printf("%d", u);   // uninitialised read

Each of these lines is undefined behavior or, for the last one, erroneous behavior since C++26. The first four are the cases a reader asked about. The series has so far looked at one tool per episode: constexpr, contract_assert and saturating and checked arithmetic. This episode runs every case under every tool and puts the results in one table. The reader was Zamfir Yonchev, in a comment on our Facebook post; the first episode quotes his question.

In short

  • Seven undefined statements run under seven checking mechanisms on GCC 16.2. One table shows which mechanism stops, which only reports, and which says nothing.
  • Constexpr stops all seven rows, but only for code evaluated in a constant expression.
  • Among the six run-time columns, none stops or reports for all seven rows.
  • The uninitialised read is the one row where nothing reports at run time. Erroneous behavior gives it a defined value.
  • No tool is an operator on a single expression. Each one checks a different unit.

How the matrix was run

All results are from GCC 16.2.0 with -std=c++26 -Wall -Wextra, on Compiler Explorer (x86-64, g162) unless a table says otherwise. The same script ran in the gcc:16.2 Docker image (aarch64) and its differences are listed below. The cases are in ub_cases_matrix.cpp, the commands in run_matrix.sh. Operands come from volatile variables so the compiler cannot fold them. The vector has three elements and capacity three.

What each statement does with no tool

statement -O0 -O2 aarch64 -O2
v[3] (vector) abort, exit 134 prints 0, exit 0 prints 0, exit 0
a[3] (built-in array) prints 0 prints 32765 prints 0
INT_MAX + 1 -2147483648 -2147483648 -2147483648
10 / 0 SIGFPE SIGFPE prints 0, exit 0
*p, p null SIGSEGV SIGSEGV SIGSEGV
*up, empty unique_ptr abort, exit 134 SIGSEGV SIGSEGV
int u; read 0 0 0

Two rows have a library check at -O0: the vector and the unique_ptr. The macro _GLIBCXX_ASSERTIONS is on by default when __OPTIMIZE__ is not defined. So the -O0 column is not a build with no checks for those two. On aarch64 the integer division by zero did not trap: 10 / 0 printed 0 and the program exited 0. At -std=c++23 -O0, the uninitialised int also printed 0 there. On x86-64 it printed 32765. The out-of-range values for a[3] are whatever sat next to the array, and they changed between platforms and optimisation levels.

One table, seven mechanisms

The cell wording means this:

  • stops: the build fails, or the run ends with a message naming the cause.
  • reports: a diagnostic is printed and the run goes on to the undefined statement.
  • silent: tested, no diagnostic from the tool.

The contract_assert column uses the default enforce semantic and a predicate written for each statement:

statement predicate
v[3] i < v.size()
a[3] i < 3
INT_MAX + 1 x < INT_MAX
10 / 0 d != 0
*p, null p != nullptr
*up, empty up != nullptr

The main table follows:

statement constexpr contract_assert _GLIBCXX_ASSERTIONS UBSan ASan -ftrapv erroneous behavior
v[3] stops, compile time stops (observe reports) stops silent stops silent not applicable
a[3] stops, compile time stops (observe reports) silent reports stops silent not applicable
INT_MAX + 1 stops, compile time stops (observe reports) silent reports silent stops not applicable
10 / 0 stops, compile time stops (observe reports) silent reports, then SIGFPE stops, names the signal silent not applicable
*p, null stops, compile time stops (observe reports) silent reports, then SIGSEGV stops, names the signal silent not applicable
*up, empty stops, compile time stops (observe reports) stops reports, then SIGSEGV stops, names the signal silent not applicable
int u; read stops, compile time untested silent silent silent silent defines it as 0

Each column adds the flags below to the base option -std=c++26:

column flags
constexpr -DCONSTEVAL_CHECK=n (the statement inside a static_assert)
contract_assert -DGUARD with -lstdc++exp
_GLIBCXX_ASSERTIONS -D_GLIBCXX_ASSERTIONS
UBSan -fsanitize=undefined
ASan -fsanitize=address
-ftrapv -ftrapv
erroneous behavior no flag

Every run except the constexpr one used -O2. The -ftrapv column was the same at -O0 for overflow, where it aborts.

What each tool printed

The table gives the text each tool printed:

tool text printed
constexpr call to non-'constexpr' function 'void std::__glibcxx_assert_fail(...)' for the vector and unique_ptr; array subscript value '3' is outside the bounds of array 'a' of type 'int [3]'; overflow in constant expression [-fpermissive]; '(10 / 0)' is not a constant expression; dereferencing a null pointer; for the uninitialised read the value of 'u' is not usable in a constant expression
contract_assert contract violation in function int main() at ...: i < v.size()
_GLIBCXX_ASSERTIONS stl_vector.h:1253: ... Assertion '__n < this->size()' failed. and unique_ptr.h:474: ... Assertion 'get() != pointer()' failed.
UBSan (-fsanitize=undefined) index 3 out of bounds for type 'int [3]'; signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'; division by zero; load of null pointer of type 'int'; for the unique_ptr reference binding to null pointer of type 'int' followed by load of null pointer of type 'int'
ASan (-fsanitize=address) heap-buffer-overflow ... 0 bytes after 12-byte region for the vector and stack-buffer-overflow for the array, both exit 1; for division and null AddressSanitizer:DEADLYSIGNAL, then FPE on unknown address or SEGV on unknown address 0x000000000000, exit 1
-ftrapv Program terminated with signal SIGABRT (6) for INT_MAX + 1 at -O0 and -O2

Notes on the cells, one tool at a time:

  • constexpr. The messages are the ones from the first episode. It stops only when the call is evaluated in a constant expression. The run-time rows of the first table are the same functions without that.
  • Contract assertion. With enforce, every guarded statement ended in exit 134 after the contract violation message. With observe, the report was printed and the statement ran. The vector, array and overflow statements printed their values and exited 0. Division by zero ended in SIGFPE and the two null cases in SIGSEGV on x86-64. The aarch64 division printed 0. There is no predicate in the standard library for “this local was initialised”, so that cell is untested rather than a claim.
  • Library assertions. Both messages end in SIGABRT. The macro covers calls into the library. It says nothing about the built-in array, signed overflow, integer division by zero or a raw pointer dereference. The longer story is in the hardened standard library post.
  • UBSan. The vector index was silent and exited 0. The reports do not stop the run. Overflow and the array index exited 0, and division and null went on to SIGFPE and SIGSEGV.
  • ASan. For division and null, the output is a report of the signal, with a stack trace, and it names no cause in the source. Overflow and the uninitialised read were silent.
  • Trapping overflow. The option has no effect on the other rows. The third episode covers the comparison x + 1 > x. It still prints 1 with -ftrapv at -O2.

Erroneous behavior

At -O0 the uninitialised read printed these values:

build printed
-std=c++26 0
-std=c++23 32765
-std=c++26 -ftrivial-auto-var-init=uninitialized 32767
-ftrivial-auto-var-init=pattern -16843010
[[indeterminate]] int u; at -O0 32765
[[indeterminate]] int u; at -O2 0

The first four values are defined values, not diagnostics. The last two rows show that the attribute brings the undefined read back. The semantics are in the erroneous behavior post.

The statements that finish without a trap

The demo below is ub_matrix_embed.cpp. It guards the index and the overflow with a contract_assert under observe. It reads inside the vector’s capacity, so the index does not trap. It also reads an uninitialised local, and the program exits 0:

index: statement ran
overflow: INT_MAX + 1 = -2147483648
uninitialised: u = 0
contract violation in function int main() at /app/example.cpp:18: i < v.size()
[assertion_kind: assert, semantic: observe, mode: predicate_false, terminating: no]
contract violation in function int main() at /app/example.cpp:24: x < INT_MAX
[assertion_kind: assert, semantic: observe, mode: predicate_false, terminating: no]

The two reports go to stderr, so their position relative to the other three lines depends on how the streams are merged. The option -Wall also warns at -O2. The warning reads 'u' may be used uninitialized. The cases that trap or abort are in run_matrix.sh and not in the embed.

What none of them gives you

No expression-level operator exists in C++26 that checks one subexpression and picks its own failure. One such shape would be vec[i] ?? throw std::out_of_range. None of the tools above has it. Each mechanism in the table has a different unit:

  • constexpr checks a whole constant evaluation and nothing at run time;
  • A contract_assert statement sits beside the statement that can fail, checks a predicate you write, and has no form for an uninitialised read;
  • The _GLIBCXX_ASSERTIONS macro checks calls into the library;
  • UBSan, ASan and -ftrapv instrument the whole translation unit, and each covers a different subset of the rows.

The constexpr column is stops for all seven rows, but only for code evaluated in a constant expression. Among the six run-time columns, none is stops or reports for all seven rows. The uninitialised read is the one row where nothing in the tested set reports anything at run time. Erroneous behavior gives it a defined value, so the read stops being undefined, and the program prints 0. A later episode looks at the committee’s work on making undefined behavior in the core language a contract violation.

What this has not been tested on

  • Clang and MSVC were not run for any cell. The contract_assert column is GCC only, as in the second episode.
  • GCC versions other than 16.2.0, and optimisation levels other than -O0 and -O2.
  • Any build that combines two mechanisms, such as -fsanitize=undefined,address with -D_GLIBCXX_ASSERTIONS, except where the first table says a default is on.
  • ASan on a vector index inside the vector’s capacity, and libstdc++’s container annotations for ASan (_GLIBCXX_SANITIZE_VECTOR).
  • -fsanitize=bounds-strict and -fsanitize-trap.
  • -fhardened, MemorySanitizer, Valgrind and static analysis.
  • -ftrapv on types other than int.
  • A contract assertion that states an overflow check for an operand pair, such as a + b, instead of the one-operand predicate used here.
  • 32-bit targets, and operating systems other than the Linux of Compiler Explorer and the Docker image.
  • The contract_assert row for an uninitialised read: there is no standard predicate for it, and none was tried.

Sources (run 7 October 2026):