1
/* Like vsprintf but provides a pointer to malloc'd storage, which must
2
be freed by the caller.
3
Copyright (C) 1994, 2002 Free Software Foundation, Inc.
5
This file is part of the libiberty library.
6
Libiberty is free software; you can redistribute it and/or
7
modify it under the terms of the GNU Library General Public
8
License as published by the Free Software Foundation; either
9
version 2 of the License, or (at your option) any later version.
11
Libiberty is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
Library General Public License for more details.
16
You should have received a copy of the GNU Library General Public
17
License along with libiberty; see the file COPYING.LIB. If
18
not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19
Boston, MA 02111-1307, USA. */
30
int global_total_width;
34
vasprintf (char **result, const char *format, va_list args)
36
const char *p = format;
37
/* Add one to make sure that it is never zero, which might cause malloc
39
int total_width = strlen (format) + 1;
48
memcpy (&ap, args, sizeof (va_list));
49
#endif /* __va_copy */
56
while (strchr ("-+ #0", *p))
61
total_width += abs (va_arg (ap, int));
64
total_width += strtoul (p, (char**)&p, 10);
71
total_width += abs (va_arg (ap, int));
74
total_width += strtoul (p, (char**)&p, 10);
76
while (strchr ("hlL", *p))
78
/* Should be big enough for any format specifier except %s
90
(void) va_arg (ap, int);
97
(void) va_arg (ap, double);
98
/* Since an ieee double can have an exponent of 307, we'll
99
make the buffer wide enough to cover the gross case. */
104
char *tmp = va_arg (ap, char *);
106
total_width += strlen (tmp);
107
else /* in case the vsprintf does prints a text */
108
total_width += 25; /* e.g. "(null pointer reference)" */
113
(void) va_arg (ap, char *);
119
global_total_width = total_width;
121
*result = malloc (total_width);
123
return vsprintf (*result, format, args);
130
asprintf (char **buf, const char *fmt, ...)
136
status = vasprintf (buf, fmt, ap);
144
checkit (const char* format, ...)
149
va_start (args, format);
150
vasprintf (&result, format, args);
151
if (strlen (result) < global_total_width)
155
printf ("%d %s\n", global_total_width, result);
161
checkit ("%d", 0x12345678);
162
checkit ("%200d", 5);
163
checkit ("%.300d", 6);
164
checkit ("%100.150d", 7);
165
checkit ("%s", "jjjjjjjjjiiiiiiiiiiiiiiioooooooooooooooooppppppppppppaa\n\
166
777777777777777777333333333333366666666666622222222222777777777777733333");
167
checkit ("%f%s%d%s", 1.0, "foo", 77, "asdjffffffffffffffiiiiiiiiiiixxxxx");