5

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?

1

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

upv because this solution is better but this doesn't answer OP question
@ouah - thanks. the answer is here since OP asked in comments if I could explain that solution and it was too long for a comment.
0

I believe OP was referring to carry-out, not overflow. Overflow occurs when the addition/subtraction of two signed numbers doesn't fit into the number of type's bits size -1 (minus sign bit). For example, if an integer type has 32 bits, then adding 2147483647 (0x7FFFFFFF) and 1 gives us -2 (0x80000000).

So, the result fits into 32 bits and there is no carry-out. The true result should be 2147483648, but this doesn't fit into 31 bits. Cpu has no idea of signed/unsigned value, so it simply add bits together, where 0x7FFFFFFF + 1 = 0x80000000. So the carry of bits #31 was added to bit #32 (1 + 0 = 1), which is actually a sign bit, changed result from + to -.

Since the sign changed, the CPU would set the overflow flag to 1 and carry flag to 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.