1 /* xmalloc.c -- malloc with out of memory checking
2    Copyright (C) 1990-1996, 2000-2003, 2005-2006 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 Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17 
18 #include <config.h>
19 
20 /* Specification.  */
21 #include "xalloc.h"
22 
23 #include <stdlib.h>
24 
25 #include "error.h"
26 #include "exit.h"
27 #include "gettext.h"
28 
29 #define _(str) gettext (str)
30 
31 
32 /* Exit value when the requested amount of memory is not available.
33    The caller may set it to some other value.  */
34 int xmalloc_exit_failure = EXIT_FAILURE;
35 
36 void
xalloc_die()37 xalloc_die ()
38 {
39   error (xmalloc_exit_failure, 0, _("memory exhausted"));
40   /* The `noreturn' cannot be given to error, since it may return if
41      its first argument is 0.  To help compilers understand the
42      xalloc_die does terminate, call exit. */
43   exit (EXIT_FAILURE);
44 }
45 
46 static void *
fixup_null_alloc(size_t n)47 fixup_null_alloc (size_t n)
48 {
49   void *p;
50 
51   p = 0;
52   if (n == 0)
53     p = malloc ((size_t) 1);
54   if (p == NULL)
55     xalloc_die ();
56   return p;
57 }
58 
59 /* Allocate N bytes of memory dynamically, with error checking.  */
60 
61 void *
xmalloc(size_t n)62 xmalloc (size_t n)
63 {
64   void *p;
65 
66   p = malloc (n);
67   if (p == NULL)
68     p = fixup_null_alloc (n);
69   return p;
70 }
71 
72 /* Allocate SIZE bytes of memory dynamically, with error checking,
73    and zero it.  */
74 
75 void *
xzalloc(size_t size)76 xzalloc (size_t size)
77 {
78   void *p;
79 
80   p = xmalloc (size);
81   memset (p, 0, size);
82   return p;
83 }
84 
85 /* Allocate memory for N elements of S bytes, with error checking,
86    and zero it.  */
87 
88 void *
xcalloc(size_t n,size_t s)89 xcalloc (size_t n, size_t s)
90 {
91   void *p;
92 
93   p = calloc (n, s);
94   if (p == NULL)
95     p = fixup_null_alloc (n);
96   return p;
97 }
98 
99 /* Change the size of an allocated block of memory P to N bytes,
100    with error checking.
101    If P is NULL, run xmalloc.  */
102 
103 void *
xrealloc(void * p,size_t n)104 xrealloc (void *p, size_t n)
105 {
106   if (p == NULL)
107     return xmalloc (n);
108   p = realloc (p, n);
109   if (p == NULL)
110     p = fixup_null_alloc (n);
111   return p;
112 }
113