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.
20 #pragma ident "%Z%%M% %I% %E% SMI"
24 #ifndef HAVE_VASPRINTF
32 #define VA_COPY(dest, src) va_copy(dest, src)
35 #define VA_COPY(dest, src) __va_copy(dest, src)
37 #define VA_COPY(dest, src) (dest) = (src)
45 vasprintf(char **str
, const char *fmt
, va_list ap
)
49 char *string
, *newstr
;
53 if ((string
= malloc(INIT_SZ
)) == NULL
)
56 ret
= vsnprintf(string
, INIT_SZ
, fmt
, ap2
);
57 if (ret
>= 0 && ret
< INIT_SZ
) { /* succeeded with initial alloc */
59 } else if (ret
== INT_MAX
|| ret
< 0) { /* Bad length */
62 } else { /* bigger than initial, realloc allowing for nul */
63 len
= (size_t)ret
+ 1;
64 if ((newstr
= realloc(string
, len
)) == NULL
) {
70 ret
= vsnprintf(newstr
, len
, fmt
, ap2
);
71 if (ret
>= 0 && (size_t)ret
< len
) {
73 } else { /* failed with realloc'ed string, give up */
92 asprintf(char **str
, const char *fmt
, ...)
99 ret
= vasprintf(str
, fmt
, ap
);