物有所值:
我自己无法解决这个问题,所以我和我的编译器讨论了这个问题,他说条件等同于* if (_ptr != NULL)
:
% gcc -Wall -O2 -g -c convoluted.c; objdump -d -M intel -S convoluted.o
convoluted.o: file format elf32-i386
Disassembly of section .text.startup:
00000000 <main>:
#include <stdlib.h>
int main(void)
{
0: 55 push ebp
1: 89 e5 mov ebp,esp
3: 83 e4 f0 and esp,0xfffffff0
6: 83 ec 10 sub esp,0x10
void* _ptr=malloc(1024);
9: c7 04 24 00 04 00 00 mov DWORD PTR [esp],0x400
10: e8 fc ff ff ff call 11 <main+0x11>
if(*((void **) &(_ptr)) != (void *) NULL)
15: 85 c0 test eax,eax
17: 74 08 je 21 <main+0x21>
{
free(_ptr);
19: 89 04 24 mov DWORD PTR [esp],eax
1c: e8 fc ff ff ff call 1d <main+0x1d>
}
return 0;
}
21: 31 c0 xor eax,eax
23: c9 leave
24: c3 ret
% gcc -Wall -O2 -g -c kindanormal.c; objdump -d -M intel -S kindanormal.o
kindanormal.o: file format elf32-i386
Disassembly of section .text.startup:
00000000 <main>:
#include <stdlib.h>
int main(void)
{
0: 55 push ebp
1: 89 e5 mov ebp,esp
3: 83 e4 f0 and esp,0xfffffff0
6: 83 ec 10 sub esp,0x10
void* _ptr=malloc(1024);
9: c7 04 24 00 04 00 00 mov DWORD PTR [esp],0x400
10: e8 fc ff ff ff call 11 <main+0x11>
if(_ptr != NULL)
15: 85 c0 test eax,eax
17: 74 08 je 21 <main+0x21>
{
free(_ptr);
19: 89 04 24 mov DWORD PTR [esp],eax
1c: e8 fc ff ff ff call 1d <main+0x1d>
}
return 0;
}
21: 31 c0 xor eax,eax
23: c9 leave
24: c3 ret
注意
正如其他人指出的那样,检查本身也不是必需的。一种更自然的方法是:
免费(_ptr);_ptr=NULL;
*在这台机器上,使用这个操作系统、这个 GCC 版本和这个 CPU,并且只有当星星以正确的方式对齐时......