Tuesday, October 28, 2008

variable argument lists

I found an interesting problem with using var args today. When you implement a function that takes a variable number of arguments, you have to use a nasty little function called va_start() which gets a pointer to the first of the variable arguments that was passed on the stack to the function. See code below. In order to do this, you pass to va_start() the argument that was just before the variable arguments passed, in this case a const MyObj&.
I found that this just caused the user of the va_list to crash.
It turns out that you can't use an object reference like this, because the sizeof mechanism that determines how far to advance the pointer past the parameter thinks the parameter is as big as the object, where it is really just a reference to that object.
Solution: Pass a const MyObj* or a MyObj by value. In some functions, you could arrange the order of params so that a pointer or value is next to the var args.
Nasty.

void doStuff(const MyObj& details, ... )
{
va_list args;
va_start(args, details);
//use args
va_end(args);
}

No comments: