它是法律采取的函数参数的地址? [英] Is it legal to take the address of a function parameter?

查看:94
本文介绍了它是法律采取的函数参数的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时的ANSI C明确这code段?
在我的系统(Linux的x86_64的),它似乎运行得很好,并打印地址,但它永远是这样吗?例如。该参数可以通过寄存器传递,并利用该地址看起来不正确。

 的#include<&stdio.h中GT;无效美孚(INT一)
{
   的printf(%P \\ N,&安培; A);
}INT主要(无效)
{
   富(42);
   返回0;
}

编辑:像GCC外貌将会把由寄存器以它的地址之前传递到堆栈中的值

 <富计算值:
  55推RBP
  48 89 E5 MOV RBP,RSP
  48 83 10统分RSP,为0x10
  89 FC 7D MOV DWORD PTR [RBP-位于0x4],EDI
  B8 1C 06 40 0​​0 MOV EAX,0x40061c
  48 8D 55 FC LEA RDX,[RBP-位于0x4]
  48 89 D6 MOV RSI,RDX
  48 89 C7 MOV偏下,RAX
  B8 00 00 00 00 MOV eax中,为0x0
  E8 D8 FE FF FF通话4003c0< printf的PLT @>
  C9休假
  C3 RET


解决方案

是的,这是完全合法的 - 当然你不会从该函数返回地址,因为受时间的回报,这是毫无意义的。

Is this code snippet well defined in ANSI C? On my system (Linux x86_64) it seems to run just fine and print an address, but will it always be the case? E.g. the parameter might be passed via a register, and taking the address of that doesn't seem right.

#include <stdio.h>

void foo(int a)
{
   printf("%p\n", &a);
}

int main(void)
{
   foo(42);
   return 0;
}

EDIT: Looks like GCC will put the value that is passed by register into the stack before taking the address of it.

<foo>:
  55                      push   rbp
  48 89 e5                mov    rbp,rsp
  48 83 ec 10             sub    rsp,0x10
  89 7d fc                mov    DWORD PTR [rbp-0x4],edi
  b8 1c 06 40 00          mov    eax,0x40061c
  48 8d 55 fc             lea    rdx,[rbp-0x4]
  48 89 d6                mov    rsi,rdx
  48 89 c7                mov    rdi,rax
  b8 00 00 00 00          mov    eax,0x0
  e8 d8 fe ff ff          call   4003c0 <printf@plt>
  c9                      leave  
  c3                      ret   

解决方案

Yes, this is perfectly legal - of course you wouldn't return that address from the function, because by the time foo returns, it's meaningless.

这篇关于它是法律采取的函数参数的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆