作为使用自定义堆栈的实验的一部分,我想要一个函数来返回堆栈分配的char缓冲区的地址.
// return pointer to stack variable
void *foo(void)
{
char sz[10] = "hello";
return sz;
}
Run Code Online (Sandbox Code Playgroud)
我知道在C中执行此操作是违法的,gcc也会发出警告.
gcc -Wall -Wextra -pedantic -std=gnu99 -fomit-frame-pointer -O0 -c foo.c
foo.c:8:12: warning: function returns address of local variable [-Wreturn-local-addr]
return sz;
Run Code Online (Sandbox Code Playgroud)
尽管如此,由于这是实验的一部分,我希望代码保持原样.有趣的是生成的代码返回0而不是sz的堆栈地址:
boa@localhost:~/tmp$ objdump -dMintel foo.o
0000000000000000 <foo>:
0: 48 b8 68 65 6c 6c 6f movabs rax,0x6f6c6c6568
7: 00 00 00
a: 48 89 44 24 f0 mov QWORD PTR [rsp-0x10],rax
f: 66 c7 44 24 f8 00 00 mov WORD PTR …Run Code Online (Sandbox Code Playgroud)