According to CERT C ++ Secure Coding Standard module may overflow , he says:
[...] Overflow can occur during operations with the module, when the dividend is equal to the minimum (negative) value for the integer type with a sign, and the divisor is -1.
and they recommend that you follow the following checkout style to prevent overflow:
signed long sl1, sl2, result; if ( (sl2 == 0 ) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) { } else { result = sl1 % sl2; }
draft C ++ standard section 5.6 Multiplicative operators given in clause 4 say (emphasis mine):
The binary / operator gives the quotient, and the binary operator% gives the remainder of dividing the first expression by the second. If the second operand / or% is zero, the behavior is undefined. For integral operands, the operator / gives an algebraic relation with any fractional part discarded: 81 if the quotient a / b is representable in the result type (a / b) * b + a% b is equal to a; otherwise, the behavior of both a / b and a% b will be undefined.
The C version of the CERT document provides more details on how % works on some platforms, and in some cases INT_MIN % -1 can throw a floating point exception.
The overflow prevention logic for / is the same as in the above logic for % .
source share