Paul C
Paul C

Reputation: 8497

If you pass args from a variadic function to another function with va_list, how do you call va_start (without error)

I've seen answers here to questions on how to pass variadic args from one function to another that say use a va_list to pass to the 2nd function. Great, when I tried this, va_start doesn't like the passed in va_list passed in...

void foo(const char *str, va_list args) {
  va_start(args, str);
  //do something
  va_end(args);
}

void foo(const char *str, ...) {
  va_list args;
  foo(str, args);
}

I get this error from g++:

error: ‘va_start’ used in function with fixed args

Upvotes: 0

Views: 433

Answers (2)

M.M
M.M

Reputation: 141648

This code causes undefined behaviour as you have used args uninitialized in foo. The correct way is:

void foo(const char *str, va_list args) {
  //do something
}

void foo(const char *str, ...) {
  va_list args;
  va_start(args, str);
  foo(str, args);
  va_end(args);
}

Upvotes: 1

Macmade
Macmade

Reputation: 54059

You need to call va_start in your variadic function. Same for va_end:

void foo (const char * str, va_list args )
{
    /* ... */
}

void foo (const char * str, ... )
{
    va_list args;

    va_start( args, str );
    foo( str, args );
    va_end( args );
}

Upvotes: 3

Related Questions