考虑以下程序:
#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,但由于 a
和 b
是 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/