blob: 73791407edf57e99bfc30d27cded9c7fc05949a6 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/* $OpenBSD: asprintf.c,v 1.15 2005/10/10 12:00:52 espie 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
26int
27asprintf(char **str, const char *fmt, ...)
28{
29 int ret;
30 va_list ap;
31 FILE f;
32 unsigned char *_base;
33
34 f._file = -1;
35 f._flags = __SWR | __SSTR | __SALC;
36 f._bf._base = f._p = (unsigned char *)malloc(128);
37 if (f._bf._base == NULL)
38 goto err;
39 f._bf._size = f._w = 127; /* Leave room for the NUL */
40 va_start(ap, fmt);
41 ret = vfprintf(&f, fmt, ap);
42 va_end(ap);
43 if (ret == -1)
44 goto err;
45 *f._p = '\0';
46 _base = realloc(f._bf._base, ret + 1);
47 if (_base == NULL)
48 goto err;
49 *str = (char *)_base;
50 return (ret);
51
52err:
53 if (f._bf._base) {
54 free(f._bf._base);
55 f._bf._base = NULL;
56 }
57 *str = NULL;
58 errno = ENOMEM;
59 return (-1);
60}