1 /* Copyright (c) 2004 Darren Tucker.
3 * Based originally on asprintf.c from OpenBSD:
4 * Copyright (c) 1997 Todd C. Miller <Todd.Miller AT courtesan.com>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 //extern int vsnprintf();
26 /* Include vasprintf() if not on your OS. */
27 #ifndef HAVE_VASPRINTF
36 # define VA_COPY(dest, src) va_copy(dest, src)
38 # ifdef HAVE___VA_COPY
39 # define VA_COPY(dest, src) __va_copy(dest, src)
41 # define VA_COPY(dest, src) (dest) = (src)
49 vasprintf(char **str
, const char *fmt
, va_list ap
)
53 char *string
, *newstr
;
57 if ((string
= malloc(INIT_SZ
)) == NULL
)
60 ret
= _vsnprintf(string
, INIT_SZ
, fmt
, ap2
);
61 if (ret
>= 0 && ret
< INIT_SZ
) { /* succeeded with initial alloc */
63 } else if (ret
== INT_MAX
|| ret
< 0) { /* Bad length */
65 } else { /* bigger than initial, realloc allowing for nul */
66 len
= (size_t)ret
+ 1;
67 if ((newstr
= realloc(string
, len
)) == NULL
) {
73 ret
= _vsnprintf(newstr
, len
, fmt
, ap2
);
74 if (ret
>= 0 && (size_t)ret
< len
) {
76 } else { /* failed with realloc'ed string, give up */
93 /* Include asprintf() if not on your OS. */
95 int asprintf(char **str
, const char *fmt
, ...)
102 ret
= vasprintf(str
, fmt
, ap
);