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