c++ - 无符号整数减法的编译器警告(或静态分析)?

标签 c++ g++

考虑以下程序:

#include <iostream>

int main()
{
    unsigned int a = 3;
    unsigned int b = 7;

    std::cout << (a - b) << std::endl;  // underflow here!

    return 0;
}
在以 std::cout 开头的行中正在发生下溢,因为 a小于 b所以a-b小于 0,但由于 ab是 unsigend 所以是 a-b .
当我尝试计算两个非符号整数的差异时,是否有一个编译器标志(用于 G++)给我一个警告?
现在,人们可能会争辩说,在使用任何运算符的任何计算中都可能发生上溢/下溢。但我认为应用运算符 - 更危险至 unsigend int s 因为对于无符号整数,这个错误可能发生在相当低的(对我来说:“更常见”)数字上。
发现这些东西的(静态分析)工具也很棒,但我更喜欢编译器标志和警告。

最佳答案

GCC 不(afaict)支持它,但 Clang's UBSanitizer有以下选项 [ 重点 矿]:

-fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but it is often unintentional. This sanitizer does not check for lossy implicit conversions performed before such a computation

关于c++ - 无符号整数减法的编译器警告(或静态分析)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69077002/

相关文章:

c++ - Windows 和 Linux (x86) 上的相同二进制代码

c++ - GCC 和 ld 找不到导出的符号......但它们在那里

c++ - 打印 ppm 文件的数组时出现问题

c++ - SDL2 段错误

c++ - 为 VTK 非结构化网格声明类型为 vtkSmartPointer<vtkDataArray> 的变量的问题

makefile - 使用 '-D' 在 Makefile 中定义的标志可以在头文件中使用吗?

c++ - g++ 和 Visual Studio 中方法指针转换规则的区别

c++ - 将 QUrl 传递给 QNetworkRequest 构造函数会导致 "non-class type"编译器错误

c++ - 什么是 C 中的通用库?

c++ - 即使我解压了 4.8.1,GCC -v 也会返回 GCC 4.7.3?