Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are function arguments stored in memory?

Tags:

c

memory

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.

Here is a 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.

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.

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.

Therefore my question is (tl;dr) :

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

like image 419
Aulo Avatar asked Jul 22 '26 19:07

Aulo


1 Answers

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.

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.

like image 196
nos Avatar answered Jul 24 '26 11:07

nos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!