Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do vararg functions find out the number of arguments in machine code?

How can variadic functions like printf find out the number of arguments they got?

The amount of arguments obviously isn't passed as a (hidden) parameter (see a call to printf in asm example here).

What's the trick?

like image 482
masterxilo Avatar asked Mar 11 '11 12:03

masterxilo


People also ask

What is the purpose of Variadic functions?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

Which type is used to store the arguments when the number of arguments for a function is not constant in C?

Variable length argument is a feature that allows a function to receive any number of arguments.

What is Vararg method in Java?

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.


1 Answers

The trick is that you tell them somehow else. For printf you have to supply a format string which even contains type information (which might be incorrect though). The way to supply this information is mainly user-contract and often error-prone.

As for calling conventions: Usually the arguments are pushed onto the stack from left to right and then the backjump address at last. The calling routine clears the stack. So there is no technical need for the called routine to know the number of parameters.

EDIT: In C++0x there is a safe way (even typesafe!) to call variadic functions!

like image 151
coldfix Avatar answered Sep 30 '22 20:09

coldfix