Merge branch 'master' of /pub/scm/gpxe
[gpxe.git] / src / core / asprintf.c
blob94d7e7c437e05c057e1e974ee6d25f31b1090a6c
1 #include <stdint.h>
2 #include <stddef.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <errno.h>
7 /**
8 * Write a formatted string to newly allocated memory.
10 * @v strp Pointer to hold allocated string
11 * @v fmt Format string
12 * @v args Arguments corresponding to the format string
13 * @ret len Length of formatted string
15 int vasprintf ( char **strp, const char *fmt, va_list args ) {
16 size_t len;
17 va_list args_tmp;
19 /* Calculate length needed for string */
20 va_copy ( args_tmp, args );
21 len = ( vsnprintf ( NULL, 0, fmt, args_tmp ) + 1 );
22 va_end ( args_tmp );
24 /* Allocate and fill string */
25 *strp = malloc ( len );
26 if ( ! *strp )
27 return -ENOMEM;
28 return vsnprintf ( *strp, len, fmt, args );
31 /**
32 * Write a formatted string to newly allocated memory.
34 * @v strp Pointer to hold allocated string
35 * @v fmt Format string
36 * @v ... Arguments corresponding to the format string
37 * @ret len Length of formatted string
39 int asprintf ( char **strp, const char *fmt, ... ) {
40 va_list args;
41 int len;
43 va_start ( args, fmt );
44 len = vasprintf ( strp, fmt, args );
45 va_end ( args );
46 return len;