函数参数如何存储在内存中? [英] How are function arguments stored in memory?

查看:624
本文介绍了函数参数如何存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我试图用stdarg.h宏代替变量参数函数,也就是未知参数数目的函数,但我还是试图了解参数在内存中的存储方式.

While trying to make my own alternative to the stdarg.h macros for variable arguments functions, a.k.a. functions with an unknown number of arguments, i tried to understand the way the arguments are stored in memory.

这是MWE:

#include <stdio.h>

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

int main ()
{
  int     i, j;

  i = 3;
  j = -5;
  foo(2, i, j);
  return 0;
}

我毫无疑问地了解到函数的地址与参数的地址不在同一位置. 但是后者并不总是以相同的方式组织.

I understand without any problem that the function's address is not in the same place as the arguments' addresses. But the latter aren't always organized in the same way.

在x86_32架构(mingw32)上,我得到这种结果:

On a x86_32 architecture (mingw32), i get this kind of result :

004013B0 0028FEF0 0028FEF4 0028FEF8

这意味着地址与参数的顺序相同.

which means that the adresses are in the same order as the arguments.

但是当我这次在x86_64上运行它时,输出为:

BUT when I run it on a x86_64 this time the output is :

0x400536 0x7fff53b5f03c 0x7fff53b5f038 0x7fff53b5f034

其中地址显然是相反的争论.

Where the addresses are obviously in reverse order w.r.t. the arguments.

因此,我的问题是(tl; dr):

Therefore my question is (tl;dr) :

参数的地址是否与体系结构有关,还是与编译器有关?

Are the arguments' addresses architecture dependent, or also compiler dependent?

推荐答案

它取决于编译器.编译器供应商自然必须遵守CPU体系结构的规则.至少对于可能与另一个编译器生成的代码互操作的代码,编译器通常也遵循平台ABI.平台ABI是给定平台的调用约定,链接语义等规范.

It is compiler dependent. Compiler vendors naturally have to obey by the rules of the CPU architecture. A compiler normally obey the platform ABI as well, at least for code that could potentially interoperate with code produced by another compiler. The platform ABI is a specification of calling convention, linking semantic and much more, for a given platform.

例如linux和其他unix(如操作系统)上的编译器遵循系统V应用程序二进制接口 ,您将在第3.2.3章中找到如何将参数传递给函数(在寄存器中传递的参数从左向右传递,在内存中(堆栈上)传递的参数从右向左传递).在Windows上,此处.

E.g. compilers on linux and other unix like operating system adhere to the System V Application Binary Interface, and you'll find in chapter 3.2.3 how parameters are passed to functions (arguments passed in registers are passed left to right and arguments passed in memory(on the stack) are passed from right to left). On Windows, the rules are documented here.

这篇关于函数参数如何存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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