How are variable length argument lists implemented?

What happens internally when functions using varargs are called? Native arguments are stored on the heap or on the stack, like any other arguments. If on the stack, how does it work?

+5
source share
3 answers

In C, function arguments are pushed and popped from the stack by the caller's function. The caller function knows how many items have been pressed, and therefore, he can also return them after a call. The caller can only infer the number of arguments from other parameters, such as a format string printf().

In Pascal, for example, arguments on the stack are pulled by the called. Since the caller is not aware of the number of popped items, he cannot restore the stack to its previous state. Therefore, it is not possible to implement varargs in Pascal.

+1
source

It depends on the implementation. But, most likely, the arguments are placed on the stack one after the other (after the promotions were executed by default).

va_start, va_argetc. work by simply walking the pointer through the stack and re-interpreting the bits like any type you request.

+8
source

, .

C ( cdecl) , :

void myfunc(int one, int two, int three)

( , 0):

  .                .                0x00000000
  .                .
  .                .
  | current frame  |
  |----------------|
  | return address |
  |----------------|                   ^
  |    one         |                   | stack
  |----------------|                   | growth
  |    two         |                   | direction
  |----------------|                   |
  |    three       |
  |----------------|
  | previous frame |
         ...       
         ...                        0xFFFFFFFF

So, the first argument can be selected first (because we know its location, it is just before the return address), and I hope it contains enough information about how many other arguments are present. For example, in printf(3)and related functions, all information about other arguments is present in the format string, which is the first argument.

+5
source

All Articles