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?
The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.
In the C Programming Language, the printf function writes a formatted string to the stdout stream.
In your first case, it takes 3 arguments. In the second case, it takes 4 arguments. printf is a variadic function. It takes a variable number of arguments.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With