Please compare the following code with asprintf.c/vasprintf.c/vasnprintf.c from
gnulib. asprintf depends on vasprintf which in turn depends on vasnprintf
there. vasnprintf is non-standard and not even available on glibc, while
vsnprintf as used by my implementation is standardized by POSIX and widely
available (even on windows). Granted, we have two calls to vsnprintf in my code
vs one call to vasnprintf in the gnulib code. However, if that becomes an
issue, I would rather go for some platform-specific optimization (windows also
has a number of non-standard and possibly useful *printf functions) rather than
importing such a monster.
> +int
> +asprintf(char **strp, const char *fmt, ...)
> +{
> + va_list ap;
> + va_start(ap, fmt);
> + int result = vasprintf(strp, fmt, ap);
> + va_end(ap);
> + return result;
> +}
> +
> +int
> +vasprintf(char **strp, const char *fmt, va_list ap)
> +{
> + va_list test;
> + va_copy(test, ap);
> + int length = vsnprintf(NULL, 0, fmt, test);
> + va_end(test);
> + *strp = malloc(length + 1);
> + if (*strp == NULL)
> + return -1;
> + return vsnprintf(*strp, length + 1, fmt, ap);
> +}