2
    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.

Community
  • 1
  • 1
peeyush
  • 2,841
  • 3
  • 24
  • 43

2 Answers2

3

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.

Community
  • 1
  • 1
ams
  • 24,923
  • 4
  • 54
  • 75
3

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • On many processors, multiplications are way more efficient than divisions. I would think using a function to determine whether a product is representable would be cleaner than throwing lots of integer divides all over the place. – supercat Apr 26 '16 at 20:44