如何检查整数溢出用C? [英] How to check integer overflow in C?

查看:177
本文介绍了如何检查整数溢出用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  检测C / C整数溢出的最佳方式++

有(1):

// assume x,y are non-negative
if(x > max - y) error;

和(2):

// assume x,y are non-negative
int sum = x + y;
if(sum < x || sum < y) error;

伟驰为preferred或是否有更好的办法。

Whichs is preferred or is there a better way.

推荐答案

整数溢出(注意,在无符号整数运算永远不会溢出,就被定义为环绕式代替)在C未定义行为的典型例子。这意味着,一旦你已经执行 X + Y ,如果溢出,你已经大清洗。这是来不及做任何检查 - 你的计划可能已经坠毁。认为它喜欢被零除检查 - 如果你等待该部门已经执行后,直到检查,它已经太晚了。

Integer overflow is the canonical example of "undefined behaviour" in C (noting that operations on unsigned integers never overflow, they are defined to wrap-around instead). This means that once you've executed x + y, if it overflowed, you're already hosed. It's too late to do any checking - your program could have crashed already. Think of it like checking for division by zero - if you wait until after the division has been executed to check, it's already too late.

因此​​,这意味着方法(1)是这样做的唯一正确途径。对于最大,您可以用 INT_MAX &LT; limits.h中&GT;

So this implies that method (1) is the only correct way to do it. For max, you can use INT_MAX from <limits.h>.

如果 X 和/或可以是负的,那么事情更难 - 你需要做测试以这样的方式,测试本身不会引起溢出。

If x and/or y can be negative, then things are harder - you need to do the test in such a way that the test itself can't cause overflow.

if ((y > 0 && x > INT_MAX - y) ||
    (y < 0 && x < INT_MIN - y))
{
    /* Oh no, overflow */
}
else
{
    sum = x + y;
}

这篇关于如何检查整数溢出用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆