How to detect an overflow in C++?

喜欢而已 提交于 2019-12-04 10:14:21

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

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.

Clang provides -fsanitize=signed-integer-overflow and -fsanitize=unsigned-integer-overflow.

http://clang.llvm.org/docs/UsersManual.html#controlling-code-generation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!