2 * Copyright (c) 2004 Darren Tucker.
4 * Based originally on asprintf.c from OpenBSD:
5 * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 * Don't let systems with broken printf(3) avoid our replacements
24 * via asprintf(3)/vasprintf(3) calling libc internally.
26 #if defined(BROKEN_SNPRINTF)
27 # undef HAVE_VASPRINTF
31 #ifndef HAVE_VASPRINTF
40 vasprintf(char **str, const char *fmt, va_list ap)
44 char *string, *newstr;
48 if ((string = malloc(INIT_SZ)) == NULL)
51 ret = vsnprintf(string, INIT_SZ, fmt, ap2);
52 if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
54 } else if (ret == INT_MAX || ret < 0) { /* Bad length */
57 } else { /* bigger than initial, realloc allowing for nul */
58 len = (size_t)ret + 1;
59 if ((newstr = realloc(string, len)) == NULL) {
65 ret = vsnprintf(newstr, len, fmt, ap2);
66 if (ret >= 0 && (size_t)ret < len) {
68 } else { /* failed with realloc'ed string, give up */
86 int asprintf(char **str, const char *fmt, ...)
93 ret = vasprintf(str, fmt, ap);