当我编写一个返回对局部变量的引用的函数时,GCC会生成错误的指令.我完全知道你不应该这样做.
这是简单的代码:
#include <stdio.h>
#include <stdlib.h>
int *func()
{
int a = 100;
return &a;
}
int main()
{
printf("%p\n", func());
}
Run Code Online (Sandbox Code Playgroud)
程序的输出是"(零)".
我刚用"gcc sample.c"编译了这个,并用gdb反汇编了可执行文件:
Dump of assembler code for function func:
0x00000000004004e6 <+0>: push %rbp
0x00000000004004e7 <+1>: mov %rsp,%rbp
0x00000000004004ea <+4>: movl $0x64,-0x4(%rbp)
0x00000000004004f1 <+11>: mov $0x0,%eax
0x00000000004004f6 <+16>: pop %rbp
0x00000000004004f7 <+17>: retq
End of assembler dump.
Dump of assembler code for function main:
0x00000000004004f8 <+0>: push %rbp
0x00000000004004f9 <+1>: mov %rsp,%rbp
0x00000000004004fc <+4>: mov $0x0,%eax
0x0000000000400501 <+9>: …Run Code Online (Sandbox Code Playgroud)