2
* Copyright (C) 2010 Michael R. Elkins <me@mutt.org>
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; if not, write to the Free Software
16
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
/* NOTE: Currently there is no check in configure.ac for vasprintf(3). the
23
* undefined behavior of the error condition makes it difficult to write a safe
28
int safe_asprintf (char **strp, const char *fmt, ...)
34
n = vasprintf (strp, fmt, ap);
37
/* GNU libc man page for vasprintf(3) states that the value of *strp
38
* is undefined when the return code is -1.
42
mutt_error _("Out of memory!");
49
/* Mutt convention is to use NULL for 0-length strings */
50
FREE (strp); /* __FREE_CHECKED__ */
56
/* Allocate a C-string large enough to contain the formatted string.
57
* This is essentially malloc+sprintf in one.
59
int safe_asprintf (char **strp, const char *fmt, ...)
64
*strp = safe_malloc (rlen);
69
n = vsnprintf (*strp, rlen, fmt, ap);
73
FREE (strp); /* __FREE_CHECKED__ */
79
/* reduce space to just that which was used. note that 'n' does not
80
* include the terminal nul char.
82
if (n == 0) /* convention is to use NULL for zero-length strings. */
83
FREE (strp); /* __FREE_CHECKED__ */
84
else if (n != rlen - 1)
85
safe_realloc (strp, n + 1);
88
/* increase size and try again */
90
safe_realloc (strp, rlen);
94
#endif /* HAVE_ASPRINTF */