Building on Sylvain's answer, here is a simple implementation with both asprintf()
and vasprintf()
because where you need one, you usually end up needing the other too. And, given the va_copy()
macro from C99, it is easy to implement asprintf()
in terms of vasprintf()
. Indeed, when writing varargs functions, it is very often helpful to have them in pairs, one with the ellipsis notation and one with the va_list
argument in place of the ellipsis, and you trivially implement the former in terms of the latter.
This leads to the code:
int vasprintf(char **ret, const char *format, va_list args)
{
va_list copy;
va_copy(copy, args);
/* Make sure it is determinate, despite manuals indicating otherwise */
*ret = NULL;
int count = vsnprintf(NULL, 0, format, args);
if (count >= 0)
{
char *buffer = malloc(count + 1);
if (buffer == NULL)
count = -1;
else if ((count = vsnprintf(buffer, count + 1, format, copy)) < 0)
free(buffer);
else
*ret = buffer;
}
va_end(copy); // Each va_start() or va_copy() needs a va_end()
return count;
}
int asprintf(char **ret, const char *format, ...)
{
va_list args;
va_start(args, format);
int count = vasprintf(ret, format, args);
va_end(args);
return(count);
}
The tricky part of using these functions in a system where they are not provided is deciding where the functions should be declared. Ideally, they'd be in <stdio.h>
, but then you wouldn't need to write them. So, you have to have some other header which includes <stdio.h>
but declares these functions if they are not declared in <stdio.h>
. And, ideally, the code should semi-automatically detect this. Maybe the header is "missing.h"
, and contains (in part):
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdarg.h>
#ifndef HAVE_ASPRINTF
extern int asprintf(char **ret, const char *format, ...);
extern int vasprintf(char **ret, const char *format, va_list args);
#endif /* HAVE_ASPRINTF */
Also, note that this man page for asprintf() says that the return value in the pointer is indeterminate in case of error. Other man pages, including the one referenced in the question, indicate that it is explicitly set to NULL on error. The C Standard committee document (n1337.pdf) does not specify the error behaviour on lack of memory.
- If using asprintf(), do not assume that the pointer is initialized if the function fails.
- If implementing asprintf(), ensure that the pointer is set to null on error to give deterministic behaviour.
asprintf()
says that the return value in*resultp
is indeterminate in case of error. Other man pages, such as the one referenced in the question, indicate that it is explicitly set to NULL on error. If usingasprintf()
, do not assume that the pointer is initialized if the function fails. If implementingasprintf()
, ensure that the pointer is set to null on error to give deterministic behaviour. – Quietism