cunsignedinteger-overflowunsigned-integer

Detecting if an unsigned integer overflow has occurred when adding two numbers


This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.

The max value of unsigned int (UINT_MAX) on my system is 4294967295.

void check_addition_overflow(unsigned int a, unsigned int b) {
   if (b > (UINT_MAX - a)) {
     printf("overflow has occured\n");
   }
}

This seems to work with the values I've tried.

Any rogue cases? What do you think are the pros and cons?


Solution

  • You could use

    if((a + b) < a)
    

    The point is that if a + b is overflowing, the result will be trimmed and must be lower then a.

    Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):

    b can be 9 at the most. For any value a such that a + b >= 10, (a + 9) % 10 < a.
    For any values a, b such that a + b < 10, since b is not negative, a + b >= a.