6

I'm trying to wrap printf in a C program (well, actually _snprintf but this example is simpler) and am having trouble getting the variable argument stuff to work. Here is my code:

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

void works(void)
{
    printf("%d\n", 100);
}

void wrap_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    printf(fmt, args);
    va_end(args);
}

void broken(void)
{
    wrap_printf("%d\n", 100);
}

int main(void)
{
    works();
    broken();
    return 0;
}

Here is my output:

100
3668388

The args variable looks good after the call to va_start in my code, but as soon as I step into the C runtime code and they call va_start the value looks bad. Any thoughts as to what I might be doing wrong?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
user1421964
  • 63
  • 1
  • 3
  • possible duplicate of [call printf using va_list](http://stackoverflow.com/questions/5977326/call-printf-using-va-list) – Bo Persson May 28 '12 at 15:13

2 Answers2

10
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);

You need to call vprintf instead of printf. The v*printf functions understand va_List arguments. I'm surprised you didn't get a warning.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
5

You're passing args which is a va_list, but printf() of course expects the arguments directly, it has no way of knowing that its second argument suddenly is a va_list.

You should be using vprintf(), the variable-argument version which does indeed expect a va_list and knows how to extract the values from it.

unwind
  • 391,730
  • 64
  • 469
  • 606