Sun Jun 9 01:11:49 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu>
[glibc.git] / locale / programs / xmalloc.c
blob2680b8a16093c061cb0e90f419810b056ba2333c
1 /* xmalloc.c -- malloc with out of memory checking
2 Copyright (C) 1990, 91, 92, 93, 94, 95 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)
7 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, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
22 #if __STDC__
23 #define VOID void
24 #else
25 #define VOID char
26 #endif
28 #include <sys/types.h>
30 #if STDC_HEADERS || _LIBC
31 #include <stdlib.h>
32 #else
33 VOID *calloc ();
34 VOID *malloc ();
35 VOID *realloc ();
36 void free ();
37 #endif
39 #include <libintl.h>
40 #include "error.h"
42 #ifndef _
43 # define _(str) gettext (str)
44 #endif
46 #ifndef EXIT_FAILURE
47 #define EXIT_FAILURE 4
48 #endif
50 /* Exit value when the requested amount of memory is not available.
51 The caller may set it to some other value. */
52 int xmalloc_exit_failure = EXIT_FAILURE;
54 static VOID *
55 fixup_null_alloc (n)
56 size_t n;
58 VOID *p;
60 p = 0;
61 if (n == 0)
62 p = malloc ((size_t) 1);
63 if (p == 0)
64 error (xmalloc_exit_failure, 0, _("memory exhausted"));
65 return p;
68 /* Allocate N bytes of memory dynamically, with error checking. */
70 VOID *
71 xmalloc (n)
72 size_t n;
74 VOID *p;
76 p = malloc (n);
77 if (p == 0)
78 p = fixup_null_alloc (n);
79 return p;
82 /* Allocate memory for N elements of S bytes, with error checking. */
84 VOID *
85 xcalloc (n, s)
86 size_t n, s;
88 VOID *p;
90 p = calloc (n, s);
91 if (p == 0)
92 p = fixup_null_alloc (n);
93 return p;
96 /* Change the size of an allocated block of memory P to N bytes,
97 with error checking.
98 If P is NULL, run xmalloc. */
100 VOID *
101 xrealloc (p, n)
102 VOID *p;
103 size_t n;
105 if (p == 0)
106 return xmalloc (n);
107 p = realloc (p, n);
108 if (p == 0)
109 p = fixup_null_alloc (n);
110 return p;