asprintf(), vasprintf() — Print to allocated string

Standards

Standards / Extensions C or C++ Dependencies
z/OS® UNIX both  

Format

#define _XPLATFORM_SOURCE
#include <stdio.h>

int asprintf(char **strp, const char *fmt, ...); 
int vasprintf(char **strp, const char *fmt, va_list ap); 

General description

asprintf() and vasprintf() are analogs of sprintf() and vsprintf(), except that they allocate a string that is large enough to hold the output including the terminating NULL byte, and return a pointer to it via the first argument. This pointer must be passed to free() to release the allocated storage when it is no longer needed.

Returned value

If successful, asprintf() and vasprintf() return the number of bytes that are printed, same as sprintf().

If memory allocation is not possible, or some other error occurs, asprintf() and vasprintf() return -1 and the content of strp is undefined.

Related information