Use this tag for questions about the C asprintf and vasprintf extension functions for memory-safe data formatting.
asprintf
is a common C runtime function provided as an extension to the Standard C Library. It was originally provided by GLIBC, but has since made its way into a variety of vendor-provided C runtime libraries. 3rd-party implementations exist for virtually every platform.
asprintf
has a variadic version called vasprintf
, which correlates in use to the standard vsprintf
function, taking the asprintf
semantics for buffer and return value. Henceforth, both will simply be referred to as asprintf
, except where there are differences worth noting.
On GLIBC environments, such as Linux, asprintf
is available from stdio.h
, like its sprintf
counterpart, as such:
#include <stdio.h>
Other libraries, and in particular 3rd-party libraries, require different header files included to use asprintf
.
The function signatures are:
int asprintf(char **strp, const char *fmt, ...);
int vasprintf(char **strp, const char *fmt, va_list ap);
The asprintf
function may be used similarly to the C Standard sprintf
, except that an allocated buffer is not provided to the function, but is allocated by it. The buffer is allocated dynamically, so must also be explicitly free
d. The return value is the length of the allocated buffer, and the buffer is returned via strp
. On failure, the return value is -1
, and the contents of strp
are undefined.
For usage, consider this example code snippet:
char *str = NULL;
int size = asprintf(&str, "this is a %s", "test");
printf("%s\n", str); // this is a test
printf("%d\n", size); // 14
free(str);
This will print the following:
this is a test
14
Additional Resources