Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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

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

like image 468
Kingamere Avatar asked Nov 26 '15 23:11

Kingamere


People also ask

How is overflow detected for addition of unsigned numbers?

Overflow Detection – So overflow can be detected by checking Most Significant Bit(MSB) of two operands and answer. But Instead of using 3-bit Comparator Overflow can also be detected using 2 Bit Comparator just by checking Carry-in(C-in) and Carry-Out(C-out) from MSB's. Consider N-Bit Addition of 2's Complement number.

How do you know if an addition has an overflow?

The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.

When two 2 unsigned numbers are added an overflow is detected from which of the most significant position?

When two unsigned numbers are added an overflow is detected from the end carry out of the most significant position.

How do you find integer overflow on addition?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1.


1 Answers

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.

like image 78
Amit Avatar answered Sep 30 '22 15:09

Amit