Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic overflow detection in C++? [duplicate]

Tags:

c++

overflow

Possible Duplicate:
Best way to detect integer overflow in C/C++

Oftentimes when I've coded something in C++ using large numbers I can't tell when overflow is occurring, even if I am using something like a long long or other 64-bit data type. Is there an effective way to detect when overflow is occurring than witnessing erroneous values?

like image 975
John Smith Avatar asked Jun 02 '12 19:06

John Smith


People also ask

Does C detect overflow?

Beware that signed int overflow is undefined behaviour in C and C++, and thus you have to detect it without actually causing it. For signed int overflow before addition, see Detecting signed overflow in C/C++.

How do you fix arithmetic overflow in C?

There are two ways to get around this: Cast the numbers to a bigger integer type, then do the addition there, and check if the result is in the right range. Do the addition normally, then check the result (e.g. if (a+23<23) overflow).

How do you detect 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.

What happens when there is an overflow in C?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).


1 Answers

There may not be much that you would get from standard C++:

5 Expressions

4 If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

Your best bet is to probably use the standard fixed width integer types defined in <cstdint> such as uint32_t.

Take a look at the <cerrno> header too for error codes such as EOVERFLOW. There are then the overflow_error/underflow_error classes from <stdexcept>.

like image 89
dirkgently Avatar answered Oct 12 '22 21:10

dirkgently