问题
int isOverflow(uint a, uint b) {
// a and b are unsigned non-zero integers.
uint c = a * b;
if (c < ( a > b ? a : b))
return 1;
else
return 0;
}
Am I missing something ? I think the above snippet will work.
EDIT : I have seen other solutions like multiplication of large numbers, how to catch overflow which uses some fancy methods to check it. But to me above simple solution also looks correct. Thats why I am asking this question.
回答1:
It's easy to prove this is wrong by finding an exception:
Consider these two 8-bit unsigned values: a = 0x1F and b = 0xF.
c = a * b
c = 0x1F * 0xF
c = 0xD1 (Overflow! The real answer is 0x1D1)
c < ( a > b ? a : b)
0xD1 < 0x1F => False (Wrong!)
A correct answer is here.
回答2:
CERT has a great document INT30-C. Ensure that unsigned integer operations do not wrap which covers all the cases of unsigned integer overflow and check they advocate for multiplications requires that you test before you perform the multiplication to prevent the overflow before it occurs (I modified the example to fit your questions):
if (a > SIZE_MAX / b) {
/* Handle error condition */
}
c = a * b;
This is a straight forward solution to your problem, it has been solved and you should use the solutions that have been proven to work, coming up with your own solutions can be error prone.
来源:https://stackoverflow.com/questions/19902178/does-this-condition-suffice-for-overflow-check-in-multiplication