bug.c
#include <stdio.h>
int main()
{
int x = 0x7fffffff;
printf("%x\n", x);
printf("%x\n", ~x);
printf("%x\n", ~x + ~x);
printf("%x\n", !(~x + ~x));
}
我使用 编译gcc -m32 bug.c -o bug 这输出:
7fffffff
80000000
0
0
它应该输出7fffffff
80000000
0
1
我在 Ubuntu 20.04 上使用 gcc 9.3 和 gcc-multilib。我还用 gcc8 和 gcc10 对此进行了测试。当我使用 clang 时,输出是正确的。有谁知道为什么会这样?
最佳答案
使用 -Wall -Wextra -pedantic -fanalyzer -fsanitize=undefined
启用所有警告和未定义行为清理程序选项,你会看到 gcc 输出这个错误
example.cpp:8:11: runtime error: signed integer overflow: -2147483648 * 2 cannot be represented in type 'int'
您还可以指定更多这样的 sanitizer -fsanitize=signed-integer-overflow,leak,undefined,address
查看 Compiler Explorer 上的演示.请注意,Clang 还报告了 UB:example.cpp:8:23: runtime error: signed integer overflow: -2147483648 + -2147483648 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior example.cpp:8:23 in
example.cpp:9:25: runtime error: signed integer overflow: -2147483648 + -2147483648 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior example.cpp:9:25 in
关于c - 为什么按位运算的 gcc-multilib 输出不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66359945/