GNU shell utilities
[gnulib.git] / lib / xmalloc.c
1 /* xmalloc.c -- malloc with out of memory checking
2    Copyright (C) 1990, 91, 92, 93, 94 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
21
22 #if __STDC__
23 #define VOID void
24 #else
25 #define VOID char
26 #endif
27
28 #include <sys/types.h>
29
30 #if STDC_HEADERS
31 #include <stdlib.h>
32 #else
33 VOID *malloc ();
34 VOID *realloc ();
35 void free ();
36 #endif
37
38 #ifndef EXIT_FAILURE
39 #define EXIT_FAILURE 1
40 #endif
41
42 /* Exit value when the requested amount of memory is not available.
43    The caller may set it to some other value.  */
44 int xmalloc_exit_failure = EXIT_FAILURE;
45
46 #if __STDC__ && (HAVE_VPRINTF || HAVE_DOPRNT)
47 void error (int, int, const char *, ...);
48 #else
49 void error ();
50 #endif
51
52 static VOID *
53 fixup_null_alloc (n)
54      size_t n;
55 {
56   VOID *p;
57
58   p = 0;
59   if (n == 0)
60     p = malloc ((size_t) 1);
61   if (p == 0)
62     error (xmalloc_exit_failure, 0, "memory exhausted");
63   return p;
64 }
65
66 /* Allocate N bytes of memory dynamically, with error checking.  */
67
68 VOID *
69 xmalloc (n)
70      size_t n;
71 {
72   VOID *p;
73
74   p = malloc (n);
75   if (p == 0)
76     p = fixup_null_alloc (n);
77   return p;
78 }
79
80 /* Change the size of an allocated block of memory P to N bytes,
81    with error checking.
82    If P is NULL, run xmalloc.  */
83
84 VOID *
85 xrealloc (p, n)
86      VOID *p;
87      size_t n;
88 {
89   if (p == 0)
90     return xmalloc (n);
91   p = realloc (p, n);
92   if (p == 0)
93     p = fixup_null_alloc (n);
94   return p;
95 }