tags:

views:

641

answers:

5

Hi,

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!

+2  A: 

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

JaredPar
+5  A: 

Consider using boosts numeric conversion which gives you negative_overflow and positive_overflow exceptions (examples).

Georg Fritzsche
+1. not only does this seem like a good solution, but I learned that "negative overflow" and "underflow" are not the same thing... silly me.
rmeador
+2  A: 

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.

Stephen Canon
+1  A: 

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.

Niels Basjes