且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测C / C ++整数溢出没有有用和可靠的方式?

更新时间:2023-11-10 13:41:28

GCC开发是完全正确的位置。当标准说,行为是不确定的,这意味着恰好有在编译器的要求。

The gcc developers are entirely correct here. When the standard says that the behavior is undefined that means exactly that there are no requirements on the compiler.

作为一个有效的程序不能做任何导致UB(因为那就不再有效),编译器可以很好地认为UB不会发生。如果它仍然没有,什么编译器将是确定的。

As a valid program can not do anything that causes UB (as then it would not be valid anymore), the compiler can very well assume that UB doesn't happen. And if it still does, anything the compiler does would be ok.

有关您的问题有溢水口,一种解决方案是要考虑caclulations都应该办理什么范围。例如,平衡我的银行帐户时,我可以假设的金额将远低于1十亿,所以32位int会工作。

For your problem with overflow, one solution is to consider what ranges the caclulations are supposed to handle. For example, when balancing my bank account I can assume that the amounts would be well below 1 billion, so a 32-bit int will work.

有关你的应用领域你也许可以做些类似的预测准确的其中的溢出是可能的。然后你就可以在这些点上添加支票或选择其他数据类型(如果可用)。

For your application domain you can probably do similar estimates about exactly where an overflow could be possible. Then you can add checks at those points or choose another data type, if available.