Some gloomy C for the weekend.
int always_greater(int x) {
return x + 1 > x;
}
You would say: for INT_MAX, x + 1 wraps around and the answer is 0. In C, signed integer overflow is undefined behaviour, so the compiler is allowed to assume it never happens. If it never happens, x + 1 > x is true for every x it has to care about, and at -O2 GCC and Clang compile the function to "return 1". Look at the assembly:
always_greater:
mov eax, 1
ret
The check you thought you had written is gone. The same reasoning rewrites overflow checks written as if (a + b < a) for signed a and b: the compiler may reduce it to b < 0, which no longer detects the overflow at all.
For unsigned types the standard defines wraparound, so x + 1 > x is false for the maximum value and the compiler must keep it.
What to do:
- Check before the operation. For
a + bwithb >= 0:if (a > INT_MAX - b). For negativebthe limit is the other end:if (a < INT_MIN - b). - Use the compiler's checked arithmetic builtins (
__builtin_add_overflow) when available. - Compile test builds with
-fsanitize=undefined, which reports the overflow at run time. -fwrapvmakes signed wrap defined, at the cost of some optimisations, and it is a flag, not a standard.
It is not the compiler being malicious. It is the compiler taking the contract literally. The contract is the part we forgot to read.