简体   繁体   English

这个检测整数加法溢出的函数实际上有用吗?

[英]Does this function for detecting integer addition overflow actually work?

While reading the comments for this question , I came across a link to the comp.lang.c FAQ that shows a "careful addition function" which purportedly detects integer overflow: 在阅读这个问题的评论时,我遇到了一个指向comp.lang.c常见问题的链接,该链接显示了一个“小心添加功能”,据称可以检测到整数溢出:

int
chkadd(int a, int b)
{
    if (INT_MAX - b < a) {
        fputs("int overflow\n", stderr);
        return INT_MAX;
    }
    return a + b;
}

How does this not overflow if b == -1 ? 如果b == -1 ,这怎么不溢出? If the assumption is that a and b are both positive, why make them int rather than unsigned int in the first place? 如果假设ab都是正数,那么为什么首先将它们int而不是unsigned int

OP has identified that INT_MAX - b may overflow, rendering the remaining code invalid for proper overflow detection. OP已经确定INT_MAX - b可能溢出,导致剩余代码无效以进行正确的溢出检测。 It does not work. 这是行不通的。

if (INT_MAX - b < a) {  // Invalid overflow detection

A method to detect overflow without UB follows: 在没有UB的情况下检测溢出的方法如下:

int is_undefined_add1(int a, int b) {
  return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a);
}

why make them int rather than unsigned int in the first place? 为什么首先让它们成为int而不是unsigned int

Changing to unsigned does not solve the problem in general . 改为unsigned并不能解决一般问题。 The range of unsigned: [0...UINT_MAX] could be half of that of int: [INT_MIN...INT_MAX] . unsigned: [0...UINT_MAX]范围unsigned: [0...UINT_MAX]可以是int: [INT_MIN...INT_MAX]一半int: [INT_MIN...INT_MAX] IOWs: INT_MAX == UINT_MAX . IOWs: INT_MAX == UINT_MAX Such systems are rare these days. 这些系统现在很少见。 IAC, changing types is not needed as coded with is_undefined_add1() . IAC,不需要使用is_undefined_add1()编码来更改类型。

Probably they just overlooked it. 可能他们只是忽略了它。 Additional links on the FAQ page seem to provide more correct code. FAQ页面上的其他链接似乎提供了更正确的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM