1 /* xmalloc.c -- malloc with out of memory checking
2 Copyright (C) 1990, 91, 92, 93, 94, 95, 96, 97 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 2, or (at your option)
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 along
15 with this program; if not, write to the Free Software Foundation, Inc., Foundation,
16 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
22 #include <sys/types.h>
41 # define EXIT_FAILURE 1
44 /* Prototypes for functions defined here. */
45 #if defined (__STDC__) && __STDC__
46 void *xmalloc (size_t n);
47 void *xcalloc (size_t n, size_t s);
48 void *xrealloc (void *p, size_t n);
51 /* Exit value when the requested amount of memory is not available.
52 The caller may set it to some other value. */
53 int xalloc_exit_failure = EXIT_FAILURE;
56 char *const xalloc_msg_memory_exhausted = "Memory exhausted";
59 void (*xalloc_fail_func) (int) = 0;
62 xalloc_fail (int size)
65 (*xalloc_fail_func) (size);
66 fprintf(stderr, "%s\n", xalloc_msg_memory_exhausted);
67 exit(xalloc_exit_failure);
70 /* Allocate N bytes of memory dynamically, with error checking. */
84 /* Allocate N bytes of memory dynamically, and set it all to zero. */
99 /* Change the size of an allocated block of memory P to N bytes,
101 If P is NULL, run xmalloc. */
114 /* Duplicate a string */
116 char *xstrdup(const char *s)
122 xalloc_fail ((int)strlen(s));
128 /* Allocate memory for N elements of S bytes, with error checking. */
142 #endif /* NOT_USED */
144 int xasprintf(char **strp, const char *fmt, ...) {
148 result = xvasprintf(strp, fmt, ap);
153 int xvasprintf(char **strp, const char *fmt, va_list ap) {
154 int result = vasprintf(strp, fmt, ap);
156 fprintf(stderr, "vasprintf() failed: %s\n", strerror(errno));
157 exit(xalloc_exit_failure);