I need to make a wrapper of vprintf, so that multiple implementations of a printf like function can be done. This code demonstrates the issue:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void print_fmt2(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
void print_fmt1(const char *fmt, ...)
{
va_list args, args_copy;
va_start(args, fmt);
va_copy(args_copy, args);
print_fmt2(fmt, args_copy);
va_end(args_copy);
va_end(args);
print_fmt2("\r\n");
}
int main ()
{
print_fmt1("test return %s %u\r\n", "is", 0);
return 0;
}
The above code, compiled with gcc 11.4, Linux, outputs:
test return 3447949600
But what I expect and want to achieve is:
test return is 0
The issue should be with usage of va_copy macro, but I can't figure out what is wrong.
I have to stick to C99 standard.
Any ideas?
Thanks.
You can't do that.
That's why there's always two variants of the standard vararg functions: One vararg function, and one that takes a
va_listargument.Like in the example you show there's
vprintfto use ava_listargument. You need to do the same with your functions if you want to "cascade" them.So you need to have e.g.