You've got the right idea to use va_list
here, but if you work with va_list
you should use vasprintf
instead of asprintf
:
int _me_log(const char *fmt, ...)
{
va_list args;
char *message = NULL;
int n;
va_start(args, fmt);
n = vasprintf(&message, fmt, args);
if (n != -1 && message != NULL) {
// ... use message ...
}
free(message);
va_end(args);
return n;
}
For every routine of the printf
family, there is a variant that takes a va_list
instead of the variadic argument ...
and whose name is prefixed with the letter v
, for example:
int printf(const char *format, ...);
int vprintf(const char *format, va_list ap);
These routines exist so you can write you own (non-macro) wrapper for xprintf
.