Reverse Engineering for Beginners

(avery) #1
CHAPTER 46. VARIADIC FUNCTIONS CHAPTER 46. VARIADIC FUNCTIONS

Chapter 46


Variadic functions


Functions likeprintf()andscanf()can have a variable number of arguments. How are these arguments accessed?

46.1 Computing arithmetic mean.


Let’s imagine that we need to calculatearithmetic mean, and for some weird reason we need to specify all the values as
function arguments.

But it’s impossible to get the number of arguments in a variadic function in C/C++, so let’s denote the value of− 1 as a
terminator.

There is the standard stdarg.h header file which define macros for dealing with such arguments. Theprintf()and
scanf()functions use them as well.

#include <stdio.h>
#include <stdarg.h>

int arith_mean(int v, ...)
{
va_list args;
int sum=v, count=1, i;
va_start(args, v);

while(1)
{
i=va_arg(args, int);
if (i==-1) // terminator
break;
sum=sum+i;
count++;
}

va_end(args);
return sum/count;
};

int main()
{
printf ("%d\n", arith_mean (1, 2, 7, 10, 15, -1 /* terminator */));
};

The first argument has to be treated just like a normal argument. All other arguments are loaded using theva_argmacro
and then summed.

So what is inside?

46.1.1 cdeclcalling conventions.


Listing 46.1: Optimizing MSVC 6.0
_v$ = 8
Free download pdf