update from main archvie 961013
[glibc.git] / locale / programs / xmalloc.c
blobcbef26f7e5e0b272ff7e07b3495bb9643be88d0d
1 /* xmalloc.c -- malloc with out of memory checking
2 Copyright (C) 1990, 91, 92, 93, 94, 95, 96 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 static VOID *fixup_null_alloc __P ((size_t n));
33 VOID *xmalloc __P ((size_t n));
34 VOID *xcalloc __P ((size_t n, size_t s));
35 VOID *xrealloc __P ((VOID *p, size_t n));
36 #else
37 VOID *calloc ();
38 VOID *malloc ();
39 VOID *realloc ();
40 void free ();
41 #endif
43 #include <libintl.h>
44 #include "error.h"
46 #ifndef _
47 # define _(str) gettext (str)
48 #endif
50 #ifndef EXIT_FAILURE
51 #define EXIT_FAILURE 4
52 #endif
54 /* Exit value when the requested amount of memory is not available.
55 The caller may set it to some other value. */
56 int xmalloc_exit_failure = EXIT_FAILURE;
58 static VOID *
59 fixup_null_alloc (n)
60 size_t n;
62 VOID *p;
64 p = 0;
65 if (n == 0)
66 p = malloc ((size_t) 1);
67 if (p == 0)
68 error (xmalloc_exit_failure, 0, _("memory exhausted"));
69 return p;
72 /* Allocate N bytes of memory dynamically, with error checking. */
74 VOID *
75 xmalloc (n)
76 size_t n;
78 VOID *p;
80 p = malloc (n);
81 if (p == 0)
82 p = fixup_null_alloc (n);
83 return p;
86 /* Allocate memory for N elements of S bytes, with error checking. */
88 VOID *
89 xcalloc (n, s)
90 size_t n, s;
92 VOID *p;
94 p = calloc (n, s);
95 if (p == 0)
96 p = fixup_null_alloc (n);
97 return p;
100 /* Change the size of an allocated block of memory P to N bytes,
101 with error checking.
102 If P is NULL, run xmalloc. */
104 VOID *
105 xrealloc (p, n)
106 VOID *p;
107 size_t n;
109 if (p == 0)
110 return xmalloc (n);
111 p = realloc (p, n);
112 if (p == 0)
113 p = fixup_null_alloc (n);
114 return p;