寄存器溢出--如何控制寄存器的大小?
本帖最后由 dxcheng 于 2016-03-07 13:12 编辑运行如下demo,本来以为会出现寄存器溢出的问题,不过实际结果却不是,还请大牛们多多指教,谢谢!
// test.c
int main()
{
short c = 327;
short a = c * 2;
char r = (c + 1) * 100 / (a + 1); // (c+1)*100 本来以为这里的寄存器会产生溢出,事实上没有溢出
printf("sizeof(short):%d, sizeof(char):%d, sizeof(int):%d\n",
sizeof(short), sizeof(char), sizeof(int));
printf("r:%d\n", r);
return 0;
}
运行结果:
$gcc --version
gcc (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4)
$gcc test.c -o test -g
$./test
sizeof(short):2, sizeof(char):1, sizeof(int):4
r:50
反汇编的结果:
int main()
{
80483f4: 55 push %ebp
80483f5: 89 e5 mov %esp,%ebp
80483f7: 83 e4 f0 and $0xfffffff0,%esp
80483fa: 83 ec 30 sub $0x30,%esp
short c = 327;
80483fd: 66 c7 44 24 2a 47 01 movw $0x147,0x2a(%esp)
short a = c * 2;
8048404: 0f b7 44 24 2a movzwl 0x2a(%esp),%eax
8048409: 01 c0 add %eax,%eax
804840b: 66 89 44 24 2c mov %ax,0x2c(%esp)
char r = (c + 1) * 100 / (a + 1);
8048410: 0f bf 44 24 2a movswl 0x2a(%esp),%eax
8048415: 83 c0 01 add $0x1,%eax
8048418: 6b c0 64 imul $0x64,%eax,%eax
804841b: 0f bf 54 24 2c movswl 0x2c(%esp),%edx
8048420: 83 c2 01 add $0x1,%edx
8048423: 89 54 24 1c mov %edx,0x1c(%esp)
8048427: 89 c2 mov %eax,%edx
8048429: c1 fa 1f sar $0x1f,%edx
804842c: f7 7c 24 1c idivl0x1c(%esp)
8048430: 88 44 24 2f mov %al,0x2f(%esp)
我的疑问:
short类型的c变量,为什么在运算(c+1)*100中使用%eax寄存器,而不使用%ax寄存器?
有什么方法可以控制使用寄存器的类型吗?例如编译选项之类的。
谢谢!
这属于C语言标准里的东西 这个可能要看编绎器了吧,可能换过一种编绎器的会出现问题呢!一般编程都不会犯这种错误吧,呵呵
页:
[1]