以下代码在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;
}
所以问题在于:有符号整数溢出在技术上是未定义行为。但是在x86架构的GCC中,使用x86整数指令实现整数算术运算-在溢出时会进行包装。
因此,我本来期望它会在溢出时进行包装-尽管它是未定义行为。但这显然不是情况。那么我错过了什么?
我使用以下方式编译:
~/Desktop$ g++ main.cpp -O2
GCC 输出:
~/Desktop$ ./a.out
536870912
1073741824
-2147483648
0
0
0
... (infinite loop)
在关闭优化时,没有无限循环,输出是正确的。Visual Studio也正确编译了这个程序,并给出了以下结果:
正确输出:
~/Desktop$ g++ main.cpp
~/Desktop$ ./a.out
536870912
1073741824
-2147483648
3
以下是其他一些变体:
i *= 2; // Also fails and goes into infinite loop.
i <<= 1; // This seems okay. It does not enter infinite loop.
以下是所有相关版本信息:
~/Desktop$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ..
...
Thread model: posix
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
~/Desktop$
问题是:这是GCC的一个bug吗?还是我误解了GCC处理整数运算的方式?
*我也打上了C标签,因为我认为这个bug会在C中复现。(我还没有验证过。)
编辑:
这是循环的汇编代码:(如果我识别正确的话)
.L5:
addl %ebp, %ebp
movl $_ZSt4cout, %edi
movl %ebp, %esi
.cfi_offset 3, -40
call _ZNSolsEi
movq %rax, %rbx
movq (%rax), %rax
movq -24(%rax), %rax
movq 240(%rbx,%rax), %r13
testq %r13, %r13
je .L10
cmpb $0, 56(%r13)
je .L3
movzbl 67(%r13), %eax
.L4:
movsbl %al, %esi
movq %rbx, %rdi
addl $1, %r12d
call _ZNSo3putEc
movq %rax, %rdi
call _ZNSo5flushEv
cmpl $3, %r12d
jne .L5