c++ - 我很难理解这些关于检测整数溢出的评论

标签 c++ c integer-overflow

您将在下面的 I 部分找到引用的文本。文章简介 Understanding Integer Overflow in C/C++ (重点是我的):

Detecting integer overflows is relatively straightforward by using a modified compiler to insert runtime checks. However, reliable detection of overflow errors is surprisingly difficult because overflow behaviors are not always bugs. The low-level nature of C and C++ means that bit- and byte-level manipulation of objects is commonplace; the line between mathematical and bit-level operations can often be quite blurry. Wraparound behavior using unsigned integers is legal and well-defined, and there are code idioms that deliberately use it. On the other hand, C and C++ have undefined semantics for signed overflow and shift past bitwidth: operations that are perfectly well-defined in other languages such as Java. C/C++ programmers are not always aware of the distinct rules for signed vs. unsigned types in C, and may naively use signed types in intentional wraparound operations.1 If such uses were rare, compiler-based overflow detection would be a reasonable way to perform integer error detection. If it is not rare, however, such an approach would be impractical and more sophisticated techniques would be needed to distinguish intentional uses from unintentional ones.

我不明白为什么基于编译器的检测对于检测带符号类型的回绕操作是不切实际的,如果这种使用并不罕见的话?另外,为什么我们需要区分有意和无意的使用?两者都是标准未定义的行为。

最佳答案

在运行时检测有符号整数溢出是没有问题的。像 Swift 这样的新语言可以自动且可靠地做到这一点。

问题是:尽管整数溢出在 C 和 C++ 中是未定义的行为,但有大量代码会发生整数溢出,并且由于编译器会默默地忽略整数溢出,所以一切正常。

如果您开始检测整数溢出,这种使用会破坏应用程序。当然,这些溢出不会在开发人员运行应用程序或测试人员运行应用程序时发生,而只会在程序交付给客户时发生,如果他们的应用程序以最不适当和最昂贵的方式崩溃,他们会非常非常生气时间,只是因为您决定禁止某些工作正常的未定义行为。

关于c++ - 我很难理解这些关于检测整数溢出的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45392810/

相关文章:

c - C : initializing and inserting? 中的链表数组

c++ - 通过引用(从 `signed` 到 `unsigned` )与 `reinterpret_cast` 进行类型别名有何作用?

c++ - 当我声明字符串数组时,C++ 如何计算偏移地址

c++ - 如何在迷宫中找到最短路径?

c - 优化 O(n^2) 到 O(n)(未排序的字符串)

c - 尝试接受字符并删除空格

rust - 如何在 Rust 中返回整数溢出标志?

c - size_t 添加溢出

c++ - 使用可变参数模板函数包装基于省略号的函数

c++ - 基于用户输入的数组大小