相关疑难解决方法(0)

为什么带有GCC的x86上的整数溢出会导致无限循环?

以下代码进入GCC的无限循环:

#include <iostream>
using namespace std;

int main(){
    int i = 0x10000000;

    int c = 0;
    do{
        c++;
        i += i;
        cout << i << endl;
    }while (i > 0);

    cout << c << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以这是交易:有符号整数溢出在技术上是未定义的行为.但是x86上的GCC使用x86整数指令实现整数运算 - 它包含溢出.

因此,我本来期望它包装溢出 - 尽管事实上它是未定义的行为.但事实显然并非如此.那么我错过了什么?

我使用以下方法编译:

~/Desktop$ g++ main.cpp -O2
Run Code Online (Sandbox Code Playgroud)

GCC输出:

~/Desktop$ ./a.out
536870912
1073741824
-2147483648
0
0
0

... (infinite loop)
Run Code Online (Sandbox Code Playgroud)

禁用优化后,没有无限循环且输出正确.Visual Studio也正确编译它并给出以下结果:

正确的输出:

~/Desktop$ g++ main.cpp
~/Desktop$ ./a.out
536870912
1073741824
-2147483648
3
Run Code Online (Sandbox Code Playgroud)

以下是一些其他变体:

i *= 2;   //  Also …
Run Code Online (Sandbox Code Playgroud)

c c++ x86 gcc undefined-behavior

124
推荐指数
5
解决办法
1万
查看次数

标签 统计

c ×1

c++ ×1

gcc ×1

undefined-behavior ×1

x86 ×1