Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for signed integer overflow in C without undefined behaviour?

There's (1):

// assume x,y are non-negative if(x > max - y) error; 

And (2):

// assume x,y are non-negative int sum = x + y; if(sum < x || sum < y) error; 

Whichs is preferred or is there a better way.

like image 965
Ganker Avatar asked Apr 13 '10 22:04

Ganker


People also ask

How can you tell if a signed integer is overflow?

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. The solution of casting to long and adding to find detecting the overflow is not allowed.

Is signed integer overflow undefined?

12.2. 1 Basics of Integer Overflow In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow.

What are the conditions to detect signed overflow?

When two signed 2's complement numbers are added, overflow is detected if: both operands are positive and the sum is negative, or. both operands are negative and the sum is positive.


1 Answers

Integer overflow is the canonical example of "undefined behaviour" in C (noting that operations on unsigned integers never overflow, they are defined to wrap-around instead). This means that once you've executed x + y, if it overflowed, you're already hosed. It's too late to do any checking - your program could have crashed already. Think of it like checking for division by zero - if you wait until after the division has been executed to check, it's already too late.

So this implies that method (1) is the only correct way to do it. For max, you can use INT_MAX from <limits.h>.

If x and/or y can be negative, then things are harder - you need to do the test in such a way that the test itself can't cause overflow.

if ((y > 0 && x > INT_MAX - y) ||     (y < 0 && x < INT_MIN - y)) {     /* Oh no, overflow */ } else {     sum = x + y; } 
like image 95
caf Avatar answered Sep 19 '22 07:09

caf