1 /* Shared general utility routines for GDB, the GNU debugger.
3 Copyright (C) 1986-2013 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
26 #include "gdb_assert.h"
27 #include "gdb_string.h"
32 /* The xmalloc() (libiberty.h) family of memory management routines.
34 These are like the ISO-C malloc() family except that they implement
35 consistent semantics and guard against typical memory management
38 /* NOTE: These are declared using PTR to ensure consistency with
39 "libiberty.h". xfree() is GDB local. */
46 /* See libiberty/xmalloc.c. This function need's to match that's
47 semantics. It never returns NULL. */
51 val = malloc (size); /* ARI: malloc */
53 malloc_failure (size);
59 xrealloc (PTR ptr, size_t size) /* ARI: PTR */
63 /* See libiberty/xmalloc.c. This function need's to match that's
64 semantics. It never returns NULL. */
69 val = realloc (ptr, size); /* ARI: realloc */
71 val = malloc (size); /* ARI: malloc */
73 malloc_failure (size);
79 xcalloc (size_t number, size_t size)
83 /* See libiberty/xmalloc.c. This function need's to match that's
84 semantics. It never returns NULL. */
85 if (number == 0 || size == 0)
91 mem = calloc (number, size); /* ARI: xcalloc */
93 malloc_failure (number * size);
101 return xcalloc (1, size);
108 free (ptr); /* ARI: free */
111 /* Like asprintf/vasprintf but get an internal_error if the call
115 xstrprintf (const char *format, ...)
120 va_start (args, format);
121 ret = xstrvprintf (format, args);
127 xstrvprintf (const char *format, va_list ap)
130 int status = vasprintf (&ret, format, ap);
132 /* NULL is returned when there was a memory allocation problem, or
133 any other error (for instance, a bad format string). A negative
134 status (the printed length) with a non-NULL buffer should never
135 happen, but just to be sure. */
136 if (ret == NULL || status < 0)
137 internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
142 xsnprintf (char *str, size_t size, const char *format, ...)
147 va_start (args, format);
148 ret = vsnprintf (str, size, format, args);
149 gdb_assert (ret < size);
156 savestring (const char *ptr, size_t len)
158 char *p = (char *) xmalloc (len + 1);
160 memcpy (p, ptr, len);