Fix UBSan "Signed Integer Overflow" Runtime Errors — and Why the Optimizer Cares
A signed integer that overflows is not defined to wrap — it is undefined behavior, and the compiler is allowed to act as if it never happens. UBSan catches the overflow while the program runs and prints the exact operation, the values, and the type. Each section below takes one part of the problem, shows the exact output it produces, and gives the fix that belongs to that part.
Written November 20, 2026 · Tested with GCC 13.3.0 · 7 min read
- The first error: one past the largest int
- Why "it wraps, usually" is the wrong mental model
- The optimizer cares: a guard that -O2 removes
- The fix that widens the type
Written November 20, 2026
Tested with GCC 13.3.0
What this guide is
runtime error: signed integer overflow is UBSan, the UndefinedBehaviorSanitizer, reporting that a signed addition, subtraction, or multiplication produced a value that does not fit in its type. The program keeps running after the report by default, and it prints the wrapped value and exits with status 0 — which is why the error is easy to read as a warning and ignore. It is not a warning. Signed overflow is undefined behavior, and the rest of this guide is about the two things that follow from that: the sanitizer is reporting a real bug, and the optimizer is allowed to reason as if the overflow never happens, so a guard written against the wrapped value can disappear from the compiled program while the wrap itself stays.
The examples here use C++17 and GCC 13.3.0. Each program is a separate file in one directory. Sanitizer builds use g++ -std=c++17 -fsanitize=undefined -g and the filename; the -g is what puts the file, line, and column in the report. A runtime error prints to standard error; the program's own output prints to standard output, and the transcripts below show them in the order they appear.
The first error: one past the largest int
The smallest reproducer adds one to the largest int. std::numeric_limits<int>::max() is 2147483647 for a 32-bit int, so value += 1 needs 2147483648, which does not fit in an int:
#include <iostream>
#include <limits>
int main() {
int value = std::numeric_limits<int>::max();
value += 1;
std::cout << value << '\n';
return 0;
}
$ g++ -std=c++17 -fsanitize=undefined -g overflow.cpp -o overflow
$ ./overflow
overflow.cpp:6:11: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648
The report names the file, the line, and the column of the operation — line 6, column 11, the += — then the operation itself, with both values: 2147483647 + 1 cannot be represented in type 'int'. After the report the program carries on and prints -2147483648, the value the addition wraps to, and exits with status 0. That is the default recovery behavior: UBSan reports the error and the program continues as if nothing happened. The exit status stays 0, so a test suite that only checks the exit status passes a program with this bug in it.
To make the first report stop the program instead, build with -fno-sanitize-recover:
$ g++ -std=c++17 -fsanitize=undefined -fno-sanitize-recover -g overflow.cpp -o overflow_stop
$ ./overflow_stop
overflow.cpp:6:11: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
This time there is no -2147483648 line, and the program exits with status 1. The report is the same; the difference is that the program stops at the first error instead of recovering from it. For a test suite, the stopping form is the useful one: a run that reports an overflow fails the run.
Why "it wraps, usually" is the wrong mental model
Unsigned arithmetic is defined to wrap: adding one to the largest unsigned int gives 0, on every conforming compiler, and the program below relies on that. Signed arithmetic has no such rule. When a signed operation overflows, the behavior is undefined, and the standard leaves the compiler free to wrap the value, to trap, to saturate, or to optimize the operation away entirely. Which one happens depends on the compiler, the version, and the optimization level, and it can change between builds of the same program. Code that has run for years printing the wrapped value can start behaving differently after a compiler upgrade, with no change to the code.
That is the point of the report above. The wrapped -2147483648 is one possible outcome of undefined behavior, not the defined result of the addition. A program that depends on the wrap is depending on one compiler's choice on one day, and UBSan is the tool that finds the dependence before the choice changes.
The same check covers subtraction and multiplication, and the unary and binary forms of minus. Negating the smallest int is an overflow too: -(-2147483648) needs 2147483648, which does not fit. Dividing the smallest int by -1 is the same case in another shape, and UBSan reports it as signed integer overflow as well. One case the check does not flag is a signed char at its maximum being incremented: the value is promoted to int before the addition, so the addition happens in int and cannot overflow. Integer promotion decides what type the arithmetic happens in, and the check applies to that type.
The optimizer cares: a guard that -O2 removes
The reason the optimizer matters is that it is allowed to assume undefined behavior never happens, and it uses that assumption when it rewrites code. The loop below adds 1000000 to a running total and checks after each addition whether the total has gone negative — the check a programmer writes when they expect the total to wrap:
#include <cstdlib>
#include <iostream>
int main(int argc, char** argv) {
int n = argc > 1 ? std::atoi(argv[1]) : 0;
int total = 0;
for (int i = 0; i < n; ++i) {
total += 1000000;
if (total < 0) {
std::cout << "wrapped\n";
return 0;
}
}
std::cout << "done " << total << '\n';
return 0;
}
The total passes 2147483647 on the 2148th addition, so with n set to 3000 the wrap happens inside the loop either way. What differs is what the two builds do with the guard:
$ g++ -std=c++17 -O0 loop.cpp -o loop_o0
$ ./loop_o0 3000
wrapped
$ g++ -std=c++17 -O2 loop.cpp -o loop_o2
$ ./loop_o2 3000
done -1294967296
At -O0 the guard works as written: the total wraps negative, the check catches it, and the program prints wrapped. At -O2 the program prints done -1294967296 — the total still wrapped to a negative value, and the check that was supposed to catch it is gone. The optimizer reasoned that total starts at 0 and only ever grows by 1000000, so it can never go negative — a sound argument only if the addition cannot overflow. Since signed overflow is undefined, the compiler is entitled to assume it does not happen, and on that assumption total < 0 can never be true, so the branch is dead code and is removed. The wrap still happens in the arithmetic; only the check disappears. That is the failure mode to watch for: the program does not crash, it silently stops checking.
UBSan finds the overflow in this loop too, at the exact addition where the total passes the limit:
$ g++ -std=c++17 -fsanitize=undefined -g loop.cpp -o loop_ubsan
$ ./loop_ubsan 3000
loop.cpp:8:15: runtime error: signed integer overflow: 2147000000 + 1000000 cannot be represented in type 'int'
wrapped
The report names the addition on line 8, with the running total at that point — 2147000000 — and the amount being added. The program then recovers, the total wraps, and the guard in this unoptimized build catches it and prints wrapped.
A shorter form of the same effect is a function that asks whether adding one makes a number larger:
#include <cstdlib>
#include <iostream>
bool grows(int x) {
return x + 1 > x;
}
int main(int argc, char** argv) {
int x = argc > 1 ? std::atoi(argv[1]) : 0;
std::cout << grows(x) << '\n';
return 0;
}
$ g++ -std=c++17 -O2 grows.cpp -o grows_o2
$ ./grows_o2 2147483647
1
At the largest int, x + 1 wraps to the smallest int, which is smaller than x, so the comparison should be false. The optimized build prints 1. The comparison was folded to true during compilation: if x + 1 cannot overflow, then x + 1 is always larger than x, so the function is constant. Building the same program with -fwrapv, which defines signed overflow to wrap, restores the check:
$ g++ -std=c++17 -O2 -fwrapv grows.cpp -o grows_wrapv
$ ./grows_wrapv 2147483647
0
-fwrapv is not a fix for the bug. It changes the rules for the whole translation unit so that wrapping is defined behavior, and the program then depends on wrapping everywhere instead of in one place. It is useful as a diagnostic — it shows the difference is the optimizer's assumption, not the arithmetic — and as a stopgap for old code that cannot be fixed yet. New code should fix the arithmetic instead.
The fix that widens the type
When the real problem is range — the value is a count or a sum that can pass 2147483647 — use a type that holds it. The cast has to happen before the addition, so the addition itself is done in the wider type:
#include <iostream>
#include <limits>
int main() {
int value = std::numeric_limits<int>::max();
long long total = static_cast<long long>(value) + 1;
std::cout << total << '\n';
return 0;
}
$ g++ -std=c++17 -fsanitize=undefined -g wide.cpp -o wide
$ ./wide
2147483648
The program runs clean under UBSan and prints 2147483648. The cast is the whole fix, and its position matters. Widening the result after the addition does not help, because the overflow has already happened in int:
#include <iostream>
#include <limits>
int main() {
int value = std::numeric_limits<int>::max();
long long total = value + 1;
std::cout << total << '\n';
return 0;
}
$ g++ -std=c++17 -fsanitize=undefined -g badwide.cpp -o badwide
$ ./badwide
badwide.cpp:6:29: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648
Here value + 1 is computed in int, overflows, and is then widened to long long — widening the wrapped value, not the true one. The report points at column 29, the + on line 6. A wider type only fixes the overflow when the arithmetic itself moves into the wider type. It also only postpones the limit: a long long overflows at a larger value, so the fix belongs where the range is genuinely enough, not where the value keeps growing without bound.
The fix that uses unsigned arithmetic
When wrapping is the intended behavior — a counter that is meant to roll over, a hash, a bit pattern — the type should say so. Unsigned arithmetic is defined to wrap modulo 2 to the power of the number of bits, so the same addition that UBSan reports for int is well defined for unsigned int:
#include <iostream>
#include <limits>
int main() {
unsigned int value = std::numeric_limits<unsigned int>::max();
value += 1;
std::cout << value << '\n';
return 0;
}
$ g++ -std=c++17 -fsanitize=undefined -g unsigned.cpp -o unsigned
$ ./unsigned
0
The program runs clean under UBSan and prints 0. The change of type is a change of meaning: the value is now a quantity that wraps by definition, and the code that reads it has to treat it that way — comparisons, subtraction, and printing all behave differently for unsigned values than for signed ones. Switching a type to unsigned only to silence the sanitizer, while the rest of the program still treats the value as a signed count, trades one bug for another. Use this fix where the wrap is part of what the value means.
The fix that checks before it adds
When the result has to stay an int and the overflow has to be handled rather than avoided, check the addition with a builtin that cannot itself overflow. __builtin_add_overflow performs the addition in infinite precision, stores the result, and returns true when the result does not fit in the result type:
#include <iostream>
#include <limits>
int main() {
int value = std::numeric_limits<int>::max();
int result = 0;
if (__builtin_add_overflow(value, 1, &result)) {
std::cout << "overflow: refusing to add\n";
return 0;
}
std::cout << result << '\n';
return 0;
}
$ g++ -std=c++17 -fsanitize=undefined -g checked.cpp -o checked
$ ./checked
overflow: refusing to add
The program runs clean under UBSan — the arithmetic the builtin performs is fully defined for all argument values, so there is no overflow for the sanitizer to report — and it prints overflow: refusing to add instead of a wrapped value. The same family covers subtraction and multiplication, as __builtin_sub_overflow and __builtin_mul_overflow. The check belongs where the program has something sensible to do on overflow: refuse the input, clamp the value, or return an error. Where the program has no such branch, the check is only a louder way to find the bug, and one of the two fixes above is the right one.
A plain check written by hand works the same way, provided it never performs the overflowing operation itself: for a positive amount b, a > INT_MAX - b tests whether a + b would overflow, using only a subtraction that cannot overflow. The rule for every hand-written check is the same as for the widening fix — the check has to happen before the operation it guards, not after it. A test like a + b < a checks the result of an addition that has already overflowed, so the optimizer is free to remove it, exactly as it removed the guard in the loop above.
The exact rule: what UBSan checks, and what it does not
-fsanitize=undefined turns on the signed integer overflow check, along with the rest of the undefined-behavior checks. The overflow check covers +, *, and both the unary and binary forms of -, and it also catches INT_MIN / -1. Two related checks are not turned on by -fsanitize=undefined and have to be asked for separately: -fsanitize=float-cast-overflow, for a floating-point value converted to an integer that cannot hold it, and -fsanitize=float-divide-by-zero. A clean run under -fsanitize=undefined says nothing about either of those.
Recovery is on by default for UBSan: each error is reported and the program continues, and the exit status can stay 0. -fno-sanitize-recover reports only the first error and exits with a nonzero status. -fsanitize-trap replaces the report with a trap, for programs that cannot link the sanitizer runtime. And -ftrapv is a different mechanism from the sanitizer: it makes the compiler emit trapping code for signed overflow instead of printing a diagnostic, so it catches the overflow without a report naming the operation.
The fixes, ranked
- First, read the report: the file, line, and column name the operation, and the values name the operands. The fix belongs at that operation, not at the place the wrapped value is eventually used.
- Second, decide what the value means. A count or sum that can pass the limit wants a wider type, with the arithmetic moved into that type before it happens.
- Third, if wrapping is the intended behavior, say so with an unsigned type, and let the rest of the program treat the value as one that wraps.
- Fourth, if the result has to stay an
intand the overflow has to be handled, check with__builtin_add_overflowor a limit comparison written before the operation, and take the overflow branch. - Fifth, do not reach for
-fwrapvas the fix. It defines wrapping for the whole file and leaves the program depending on it everywhere.
Which fix for which cause
| Cause | Message | Fix |
|---|---|---|
| Adding past the largest int | Signed overflow, addition | Widen the type before adding |
| A loop guard removed at -O2 | No report, wrong output | Fix the overflow, not the guard |
| Wrapping is intended | Signed overflow, addition | Use an unsigned type |
| Result must stay int | Signed overflow, addition | Check with the overflow builtin |
Checklist
- Read the report's file, line, and column first: they name the overflowing operation, and the values in the message name its operands.
- Remember that the program continues after a UBSan report by default and can exit 0: use
-fno-sanitize-recoverin a test suite so a reported overflow fails the run. - Never write an overflow check that performs the overflowing operation: test against the limit before adding, or use the overflow builtin.
- Widen before the arithmetic, not after it: widening a wrapped result keeps the wrapped value.
- Switch to unsigned only where wrapping is what the value means, not to silence the report.
- Treat
-fwrapvas a diagnostic aid, not a fix: it defines wrapping for the whole file.
Related guides on this site
- Fix "Undefined Reference to Vtable" — the Missing Virtual Function — the companion failure at link time, where a declared virtual function is never defined and the link fails naming the vtable instead of the function.
- Fix "Multiple Definition" Link Errors — Header Definitions and inline — the companion link error, where a definition in a header is compiled into more than one translation unit.
- Fix Template "Undefined Reference" — Why Template Definitions Cannot Hide in a .cpp — the companion failure on the same builds, where a template used from another file has no visible definition to instantiate.
- Fix "Cannot Find" Library Errors — How ld Searches for Libraries, and Where the Path Is Set — the companion failure at the link step, where the library is missing from the search path rather than from the program.
- C++ Functions: Parameters, Overloads, and Default Arguments — background on C++ functions: how parameters are declared, how overloads are chosen, and what a deleted overload does to that choice.
Sources
- Instrumentation Options — for
-fsanitize=undefinedand-fsanitize=signed-integer-overflow, for the check covering+,*, and both forms of-and detectingINT_MIN / -1, for the signed-char promotion case, for recovery being on by default and-fno-sanitize-recoverstopping at the first error, and for-ftrapvtrapping where the sanitizer reports. - Integer Overflow Builtins — for
__builtin_add_overflowperforming the addition in infinite precision and returning true when the stored result differs, and for the subtraction and multiplication builtins in the same family. - Arithmetic operators — for unsigned arithmetic being performed modulo 2 to the power of the number of bits, for signed overflow being undefined behavior that may wrap, trap, saturate, or be optimized out, and for unary minus on the smallest signed value being undefined behavior.
Keep Exploring
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.
Paste sshd -G output and get a hardening verdict on the values your server actually runs.
Paste a server block and get WebSocket, TLS, HSTS, and proxy-header verdicts.
Paste a systemd timer expression and get the specific reason it fails, the normalized form, and the past-date traps the built-in check hides.
The full sysadmin hub \u2014 systemd, cgroups, file tools, and measured Linux comparisons.