gpt4 book ai didi

c++ - G++ 生成逻辑错误的汇编代码

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:10 28 4
gpt4 key购买 nike

今天我正在使用 g++ 来编译一个 c++ 文件,但是 g++ 似乎有一个问题,当一个 char 类型的变量与任何数量的 char 类型比较并且第 7 位设置为 1 时,g++ 将始终假设它是 false 因此弄错了。更具体地说,c++ 代码如下所示:

  // test.cpp
__asm__(".code16gcc \n\t");
int equals0(char i)
{
return i==0x80;
}
int equals1(char i)
{
return i==0x10;
}
int equals2(int i)
{
return i==0x80;
}

请注意,有一个序言“.code16gcc”,我用来生成实模式代码。

更具体地说,我的 g++ 版本是 cygwin 上的“g++ (GCC) 6.4.0”。

现在,使用以下命令将此文件编译成汇编代码:g++ -S -o test.s test.cpp -m32

生成的文件是:

     // some trival information is omitted
.code16gcc

.text
...
__Z7equals0c://func equals0
pushl %ebp
movl %esp, %ebp
subl $4, %esp
movl 8(%ebp), %eax
movb %al, -4(%ebp) //no comparison with 0x80
movl $0, %eax //always returns 0
leave
ret
...
__Z7equals1c://func equals1
pushl %ebp
movl %esp, %ebp
subl $4, %esp
movl 8(%ebp), %eax
movb %al, -4(%ebp)
cmpb $16, -4(%ebp) // a comparison with 0x10
sete %al
movzbl %al, %eax // returns value depend on the result of comparison
leave
ret
...
__Z7equals2i://func equals2
pushl %ebp
movl %esp, %ebp
cmpl $128, 8(%ebp) //also a comparison
sete %al
movzbl %al, %eax
popl %ebp
ret

请注意,函数 equals0 将始终返回 0(保存在 eax 中),但函数 equals1 将根据生成的汇编文件返回正确的结果。

还要注意,函数 equals0 和 equals1 之间的唯一区别是用于比较的常量,equals0 为 0x80,equals1 为 0x10。基于此,我们可以说 g++ 生成了逻辑上错误的代码。

有人知道原因并解释一下吗?

最佳答案

0x80 (int 128) 超出了有符号字符的范围 ([-128;127] ).

所以一个有符号的字符不能等于0x80

关于c++ - G++ 生成逻辑错误的汇编代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47475630/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com