Efr*_*iss 3 c gcc compiler-optimization
我创建了一个小代码,显示我遇到的错误
#include<stdlib.h>
#include<stdio.h>
int test(char * flag)
{
char flagger = *flag;
printf("test value %d", (int) flagger);
if (flagger != 0x82)
{
exit(3);
}
else
{
return 0;
}
}
int main(void)
{
char flag = 0x82, flag1 = 0x12, flag2 = 0x45;
//char buf[256];
test(&flag);
test(&flag1);
test(&flag2);
}
Run Code Online (Sandbox Code Playgroud)
编译代码时:gcc -o tester test.c或gcc -o tester test.c -O0
The resulting disassembly code for the function test in gdb is:
Dump of assembler code for function test:
0x0804849b <+0>: push ebp
0x0804849c <+1>: mov ebp,esp
0x0804849e <+3>: sub esp,0x18
0x080484a1 <+6>: mov eax,DWORD PTR [ebp+0x8]
0x080484a4 <+9>: movzx eax,BYTE PTR [eax]
0x080484a7 <+12>: mov BYTE PTR [ebp-0x9],al
0x080484aa <+15>: movsx eax,BYTE PTR [ebp-0x9]
0x080484ae <+19>: sub esp,0x8
0x080484b1 <+22>: push eax
0x080484b2 <+23>: push 0x80485c0
0x080484b7 <+28>: call 0x8048350 <printf@plt>
0x080484bc <+33>: add esp,0x10
0x080484bf <+36>: sub esp,0xc
0x080484c2 <+39>: push 0x3
0x080484c4 <+41>: call 0x8048370 <exit@plt>
End of assembler dump.
Run Code Online (Sandbox Code Playgroud)
如您所见,if被优化为始终调用exit的版本.
我尝试了很多东西(还原有条件的,使用挥发性物质等),但我没有想到为什么会发生这种情况.请帮忙?
M.M*_*M.M 12
在您的系统,范围char是-128到+127.但是0x82是130十进制的.因为130 > 127,这个测试永远不会成功.
要修复您可以使用的代码:
if ( flagger != '\x82' )
Run Code Online (Sandbox Code Playgroud)
要么
if ( (unsigned char)flagger != 0x82 )
Run Code Online (Sandbox Code Playgroud)
请注意,较早的代码char flag = 0x82是超出范围的赋值,它是实现定义的行为.您可以考虑使用unsigned char或者uint8_t使用所有这些变量.