strcpy() / strlcpy() / asprintf()
Posted Mar 30, 2012 15:56 UTC (Fri) by
nybble41 (subscriber, #55106)
In reply to:
strcpy() / strlcpy() / asprintf() by nix
Parent article:
A turning point for GNU libc
It seems to me like asprintf() should be easy to implement in terms of two calls to vsnprintf():
int vasprintf(char **strp, const char *fmt, va_list ap)
{
va_list ap_copy;
char *str;
int bytes;
char nul;
/* Determine the amount of memory required to format the string */
/* vsnprintf() returns the space required, but only stores the NUL. */
va_copy(ap_copy, ap);
bytes = vsnprintf(&nul, 1, fmt, ap_copy);
va_end(ap_copy);
if (bytes <= 0)
return bytes;
str = (char*)malloc(bytes);
if (!str)
return -1;
/* Format the string into the destination buffer */
bytes = vsnprintf(str, bytes, fmt, ap);
if (bytes <= 0)
{
free(str);
return bytes;
}
/* No errors; store pointer to destination buffer and return its size. */
*strp = str;
return bytes;
}
int asprintf(char **strp, const char *fmt, ...)
{
int bytes;
va_list ap;
va_start(ap, fmt);
bytes = vasprintf(strp, fmt, ap);
va_end(ap);
return bytes;
}
Is there any reason this implementation wouldn't work? (Ignoring minor issues/typos; I'm making this up as I go.)
(
Log in to post comments)