1 /* $OpenBSD: asprintf.c,v 1.19 2011/05/30 18:48:33 martynas Exp $ */
2
3 /*
4 * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
5 *
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.
9 *
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.
17 */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <stdarg.h>
24 #include "local.h"
25
26 /* PRINTFLIKE2 */
27 int
asprintf(char ** str,const char * fmt,...)28 asprintf(char **str, const char *fmt, ...)
29 {
30 int ret;
31 va_list ap;
32 FILE f;
33 struct __sfileext fext;
34 unsigned char *_base;
35
36 _FILEEXT_SETUP(&f, &fext);
37 f._file = -1;
38 f._flags = __SWR | __SSTR | __SALC;
39 f._bf._base = f._p = (unsigned char *)malloc(128);
40 if (f._bf._base == NULL)
41 goto err;
42 f._bf._size = f._w = 127; /* Leave room for the NUL */
43 va_start(ap, fmt);
44 ret = __vfprintf(&f, fmt, ap);
45 va_end(ap);
46 if (ret == -1)
47 goto err;
48 *f._p = '\0';
49 _base = realloc(f._bf._base, ret + 1);
50 if (_base == NULL)
51 goto err;
52 *str = (char *)_base;
53 return (ret);
54
55 err:
56 if (f._bf._base) {
57 free(f._bf._base);
58 f._bf._base = NULL;
59 }
60 *str = NULL;
61 errno = ENOMEM;
62 return (-1);
63 }
64