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.
22 #ifndef HAVE_VASPRINTF
30 # define VA_COPY(dest, src) va_copy(dest, src)
32 # ifdef HAVE___VA_COPY
33 # define VA_COPY(dest, src) __va_copy(dest, src)
35 # define VA_COPY(dest, src) (dest) = (src)
43 vasprintf(char **str
, const char *fmt
, va_list ap
)
47 char *string
, *newstr
;
51 if ((string
= malloc(INIT_SZ
)) == NULL
)
54 ret
= vsnprintf(string
, INIT_SZ
, fmt
, ap2
);
55 if (ret
>= 0 && ret
< INIT_SZ
) { /* succeeded with initial alloc */
57 } else if (ret
== INT_MAX
|| ret
< 0) { /* Bad length */
60 } else { /* bigger than initial, realloc allowing for nul */
61 len
= (size_t)ret
+ 1;
62 if ((newstr
= realloc(string
, len
)) == NULL
) {
68 ret
= vsnprintf(newstr
, len
, fmt
, ap2
);
69 if (ret
>= 0 && (size_t)ret
< len
) {
71 } else { /* failed with realloc'ed string, give up */
89 int asprintf(char **str
, const char *fmt
, ...)
96 ret
= vasprintf(str
, fmt
, ap
);