2 * Copyright (c) 2021 Elias Fleckenstein <eliasfleckenstein@web.de>
4 * Based on libressl-portable:
5 * Copyright (c) 2004 Darren Tucker.
7 * Based originally on asprintf.c from OpenBSD:
8 * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
10 * Permission to use, copy, modify, and distribute this software for any
11 * purpose with or without fee is hereby granted, provided that the above
12 * copyright notice and this permission notice appear in all copies.
14 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 #include <limits.h> /* for INT_MAX */
26 #include <stdio.h> /* for vsnprintf */
32 vasprintf(char **str, const char *fmt, va_list ap)
36 char *string, *newstr;
39 if ((string = malloc(INIT_SZ)) == NULL)
43 ret = vsnprintf(string, INIT_SZ, fmt, ap2);
45 if (ret >= 0 && ret < INIT_SZ) { /* succeeded with initial alloc */
47 } else if (ret == INT_MAX || ret < 0) { /* Bad length */
50 } else { /* bigger than initial, realloc allowing for nul */
51 len = (size_t)ret + 1;
52 if ((newstr = realloc(string, len)) == NULL) {
57 ret = vsnprintf(newstr, len, fmt, ap2);
59 if (ret < 0 || (size_t)ret >= len) { /* failed with realloc'ed string */
73 int asprintf(char **str, const char *fmt, ...)
80 ret = vasprintf(str, fmt, ap);