[contrib] Allow Network Protocol header to display in rom-o-matic
[gpxe.git] / src / core / asprintf.c
blob03cf45cfc2617eb7809fdf45fb177ee04f9d76c0
1 #include <stdint.h>
2 #include <stddef.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <errno.h>
7 FILE_LICENCE ( GPL2_OR_LATER );
9 /**
10 * Write a formatted string to newly allocated memory.
12 * @v strp Pointer to hold allocated string
13 * @v fmt Format string
14 * @v args Arguments corresponding to the format string
15 * @ret len Length of formatted string
17 int vasprintf ( char **strp, const char *fmt, va_list args ) {
18 size_t len;
19 va_list args_tmp;
21 /* Calculate length needed for string */
22 va_copy ( args_tmp, args );
23 len = ( vsnprintf ( NULL, 0, fmt, args_tmp ) + 1 );
24 va_end ( args_tmp );
26 /* Allocate and fill string */
27 *strp = malloc ( len );
28 if ( ! *strp )
29 return -ENOMEM;
30 return vsnprintf ( *strp, len, fmt, args );
33 /**
34 * Write a formatted string to newly allocated memory.
36 * @v strp Pointer to hold allocated string
37 * @v fmt Format string
38 * @v ... Arguments corresponding to the format string
39 * @ret len Length of formatted string
41 int asprintf ( char **strp, const char *fmt, ... ) {
42 va_list args;
43 int len;
45 va_start ( args, fmt );
46 len = vasprintf ( strp, fmt, args );
47 va_end ( args );
48 return len;