dmi_asprintf

Synopsis

#include <opendmi/utils/string.h>

int dmi_asprintf(char **strp, const char *format, ...);
int dmi_vasprintf(char **strp, const char *format, va_list args);

Description

The dmi_asprintf function formats its arguments according to format, as sprintf(3) does, into a string it allocates, and stores the pointer to the string in the variable strp points to. The dmi_vasprintf function does the same with the arguments given as args.

The functions behave the same on every platform: they wrap asprintf(3) and vasprintf(3) where the C library has them, and implement them on Windows, which has none.

The caller is responsible for freeing the string with free() or dmi_free.

Parameters

strp

Variable to store the pointer to the string in. On failure, it is set to nullptr, unless strp itself is nullptr.

format

Format string, see printf(3).

…​, args

Arguments of the format string.

Return value

On success, the functions return the number of bytes written, excluding the terminating null byte. On failure, they return a negative value, e.g. if strp or format is nullptr, if memory is exhausted, or if the string cannot be formatted.

Errors

DMI_ERROR_ARGUMENT_NULL

Raised if strp or format is nullptr. The functions take no context, so the error reaches no error queue.

Example

char *text = nullptr;

if (dmi_asprintf(&text, "%s, version %u", name, version) < 0)
    return false;

puts(text);
free(text);

See also

asprintf(3), printf(3), dmi_free