c - 为什么按位运算的 gcc-multilib 输出不正确?

标签 c gcc bit-manipulation undefined-behavior integer-overflow

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/

相关文章:

c++ - 为什么 auto_ptr 构造不能使用 = 语法

elixir - 如果我在尝试构建 Elixir 位串时指定现有位串的大小,则会出现参数错误

javascript - 为什么 0x80000000 >> 1 在 JavaScript 中产生负值?

c++ - GCC 在/usr/local/include 中找不到头文件

C 网络编程 - Winsock

c - 通过指针对字符串进行冒泡排序

c - 为什么我可以在 C 语言的函数参数的数组声明中编写表达式?

c - 通过 MacPorts 安装 gcc45 后,如何使用它在我的 Mac 上构建 C 语言?

C指针和位设置问题

c - 来自 C 的优化 MIPS 指令立即返回?