Blob


1 /*
2 * Copyright (c) 2015 Ingo Schwarze <schwarze@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 *
16 * This fallback implementation is not efficient:
17 * It does the formatting twice.
18 * Short of fiddling with the unknown internals of the system's
19 * printf(3) or completely reimplementing printf(3), i can't think
20 * of another portable solution.
21 */
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
27 int
28 vasprintf(char **ret, const char *format, va_list ap)
29 {
30 char buf[2];
31 va_list ap2;
32 int sz;
34 va_copy(ap2, ap);
35 sz = vsnprintf(buf, sizeof(buf), format, ap2);
36 va_end(ap2);
38 if (sz != -1 && (*ret = malloc(sz + 1)) != NULL) {
39 if (vsnprintf(*ret, sz + 1, format, ap) == sz)
40 return sz;
41 free(*ret);
42 }
43 *ret = NULL;
44 return -1;
45 }