How to detect an overflow in C++?
Question
I just wonder if there is some convenient way to detect if overflow happens to any variable of any default data type used in a C++ program during runtime? By convenient, I mean no need to write code to follow each variable if it is in the range of its data type every time its value changes. Or if it is impossible to achieve this, how would you do?
For example,
float f1=FLT_MAX+1;
cout << f1 << endl;
doesn't give any error or warning in either compilation with "gcc -W -Wall" or running.
Thanks and regards!
Solution
Consider using boosts numeric conversion which gives you negative_overflow
and positive_overflow
exceptions (examples).
OTHER TIPS
Your example doesn't actually overflow in the default floating-point environment in a IEEE-754 compliant system.
On such a system, where float is 32 bit binary floating point, FLT_MAX is 0x1.fffffep127 in C99 hexadecimal floating point notation. Writing it out as an integer in hex, it looks like this:
0xffffff00000000000000000000000000
Adding one (without rounding, as though the values were arbitrary precision integers), gives:
0xffffff00000000000000000000000001
But in the default floating-point environment on an IEEE-754 compliant system, any value between
0xfffffe80000000000000000000000000
and
0xffffff80000000000000000000000000
(which includes the value you have specified) is rounded to FLT_MAX. No overflow occurs.
Compounding the matter, your expression (FLT_MAX + 1) is likely to be evaluated at compile time, not runtime, since it has no side effects visible to your program.
In situations where I need to detect overflow, I use SafeInt<T>
. It's a cross platform solution which throws an exception in overflow situations.
SafeInt<float> f1 = FLT_MAX;
f1 += 1; // throws
It is available on codeplex
Back in the old days when I was developing C++ (199x) we used a tool called Purify. Back then it was a tool that instrumented the object code and logged everything 'bad' during a test run. I did a quick google and I'm not quite sure if it still exists.
As far as I know nowadays several open source tools exist that do more or less the same. Checkout electricfence and valgrind.
Information which may be useful on this subject:
Chapter 5 of "Secure Coding in C and C++" by Seacord
http://www.informit.com/content/images/0321335724/samplechapter/seacord_ch05.pdf
SafeInt classes for C++
http://blogs.msdn.com/david_leblanc/archive/2008/09/30/safeint-3-on-codeplex.aspx http://www.codeplex.com/SafeInt
IntSafe library for C:
http://blogs.msdn.com/michael_howard/archive/2006/02/02/523392.aspx
Source: How to detect integer overflow?
Clang provides -fsanitize=signed-integer-overflow
and -fsanitize=unsigned-integer-overflow
.
http://clang.llvm.org/docs/UsersManual.html#controlling-code-generation