1 /* vasprintf and asprintf with out-of-memory checking.
2 Copyright (C) 1999, 2002-2004, 2006, 2007 Free Software Foundation, Inc.
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 3 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, see <http://www.gnu.org/licenses/>. */
20 #include "xvasprintf.h"
29 /* Checked size_t computations. */
32 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
34 # define EOVERFLOW E2BIG
38 xstrcat (size_t argcount, va_list args)
46 /* Determine the total size. */
49 for (i = argcount; i > 0; i--)
51 const char *next = va_arg (ap, const char *);
52 totalsize = xsum (totalsize, strlen (next));
56 /* Test for overflow in the summing pass above or in (totalsize + 1) below.
57 Also, don't return a string longer than INT_MAX, for consistency with
59 if (totalsize == SIZE_MAX || totalsize > INT_MAX)
65 /* Allocate and fill the result string. */
66 result = XNMALLOC (totalsize + 1, char);
68 for (i = argcount; i > 0; i--)
70 const char *next = va_arg (args, const char *);
71 size_t len = strlen (next);
72 memcpy (p, next, len);
81 xvasprintf (const char *format, va_list args)
85 /* Recognize the special case format = "%s...%s". It is a frequently used
86 idiom for string concatenation and needs to be fast. We don't want to
87 have a separate function xstrcat() for this purpose. */
95 /* Recognized the special case of string concatenation. */
96 return xstrcat (argcount, args);
107 if (vasprintf (&result, format, args) < 0)