1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <stdarg.h>
4 
5 // From https://msdn.microsoft.com/en-us/library/28d5ce15.aspx
asprintf(char ** buf,const char * format,...)6 int asprintf(char** buf, const char* format, ...) {
7     va_list args;
8     int len;
9 
10     if (buf == NULL) {
11         return -1;
12     }
13 
14     // retrieve the variable arguments
15     va_start(args, format);
16 
17     len = _vscprintf(format, args)  // _vscprintf doesn't count
18           + 1;                      // terminating '\0'
19 
20     if (len <= 0) {
21         return len;
22     }
23 
24     *buf = (char*)malloc(len * sizeof(char));
25 
26     vsprintf(*buf, format, args);
27     return len;
28 }