I have a legacy codebase which we are trying to migrate from devtoolset-4
to devtoolset-7
. I noticed an interesting behaviour regarding overflow of signed integers (int64_t
, to be specific).
There is a code snippet which is used to detect integer overflow while multiplying a big set of integers:
// a and b are int64_t
int64_t product = a * b;
if (b != 0 && product / b != a) {
// Overflow
}
This code was working fine with devtoolset-4. However, with devtoolset-7, overflow is never being detected.
For eg: When a = 83802282034166
and b = 98765432
, the
product
becomes -5819501405344925872
(clearly the value has overflown).
But product / b
results in value equal to a (83802282034166)
. Hence the if
condition never becomes true.
Its value should have been computed based on the overflown (negative) product
value: -5819501405344925872 / 98765432 = -58922451788
Ironically, the Maths is correct but it is causing anomalous behaviour with regards to devtoolset-4.
product / b != a
to product != a * b
and reaches the same overflown value (or maybe just skips the computation based on the above statement where product = a * b
)?I understand that signed integer overflow is an 'undefined behaviour' in C++ and so the compiler behaviour could change across implementations. But could someone help me make sense of the above behaviour?
Note: the g++ versions in devtoolset-4 and devtoolset-7 are g++ (GCC) 5.2
and g++ (GCC) 7.2.1
, respectively.
Because signed overflow/underflow are classified as undefined behavior, compilers are allowed to cheat and assume it can't happen (this came up during a Cppcon talk a year or two ago, but I forget the talk off the top of my head). Because you're doing the arithmetic and then checking the result, the optimizer gets to optimize away part of the check.
This is untested code, but you probably want something like the following:
if(b != 0) {
auto max_a = std::numeric_limits<int64_t>::max() / b;
if(max_a < a) {
throw std::runtime_error{"overflow"};
}
}
return a * b;
Note that this code doesn't handle underflow; if a * b
can be negative, this check won't work.
Per Godbolt, you can see your version has the check completely optimized away.