1 
2 #ifndef _GNU_SOURCE
3 
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdarg.h>
7 
8 /*  Multiplatform implementation of asprintf() from:
9     https://stackoverflow.com/questions/40159892/using-asprintf-on-windows
10     define _GNU_SOURCE to use the GNU asprintf extension instead this one.
11 */
12 
13 
14 #include "xasprintf.h"
15 
_vscprintf_so(const char * format,va_list pargs)16 int _vscprintf_so(const char * format, va_list pargs) {
17     int retval;
18     va_list argcopy;
19     va_copy(argcopy, pargs);
20     retval = vsnprintf(NULL, 0, format, argcopy);
21     va_end(argcopy);
22     return retval;
23 }
24 
vasprintf(char ** strp,const char * fmt,va_list ap)25 int vasprintf(char **strp, const char *fmt, va_list ap) {
26     int len = _vscprintf_so(fmt, ap);
27     if (len == -1) return -1;
28     char *str = malloc((size_t) len + 1);
29     if (!str) return -1;
30     int r = vsnprintf(str, len + 1, fmt, ap);
31     if (r == -1) return free(str), -1;
32     *strp = str;
33     return r;
34 }
35 
asprintf(char * strp[],const char * fmt,...)36 int asprintf(char *strp[], const char *fmt, ...) {
37     va_list ap;
38     va_start(ap, fmt);
39     int r = vasprintf(strp, fmt, ap);
40     va_end(ap);
41     return r;
42 }
43 
44 #endif // !_GNU_SOURCE
45 
46