Update copyright notices with scripts/update-copyrights
[jlayton/glibc.git] / locale / programs / xmalloc.c
1 /* xmalloc.c -- malloc with out of memory checking
2    Copyright (C) 1990-2014 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published
7    by the Free Software Foundation; version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, see <http://www.gnu.org/licenses/>.  */
17
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
21
22 #define VOID void
23
24 #include <sys/types.h>
25
26 #if STDC_HEADERS || _LIBC
27 #include <stdlib.h>
28 static VOID *fixup_null_alloc (size_t n) __THROW;
29 VOID *xmalloc (size_t n) __THROW;
30 VOID *xcalloc (size_t n, size_t s) __THROW;
31 VOID *xrealloc (VOID *p, size_t n) __THROW;
32 #else
33 VOID *calloc ();
34 VOID *malloc ();
35 VOID *realloc ();
36 void free ();
37 #endif
38
39 #include <libintl.h>
40 #include "error.h"
41
42 #ifndef _
43 # define _(str) gettext (str)
44 #endif
45
46 #ifndef EXIT_FAILURE
47 #define EXIT_FAILURE 4
48 #endif
49
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;
53
54 static VOID *
55 fixup_null_alloc (n)
56      size_t n;
57 {
58   VOID *p;
59
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;
66 }
67
68 /* Allocate N bytes of memory dynamically, with error checking.  */
69
70 VOID *
71 xmalloc (n)
72      size_t n;
73 {
74   VOID *p;
75
76   p = malloc (n);
77   if (p == 0)
78     p = fixup_null_alloc (n);
79   return p;
80 }
81
82 /* Allocate memory for N elements of S bytes, with error checking.  */
83
84 VOID *
85 xcalloc (n, s)
86      size_t n, s;
87 {
88   VOID *p;
89
90   p = calloc (n, s);
91   if (p == 0)
92     p = fixup_null_alloc (n);
93   return p;
94 }
95
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.  */
99
100 VOID *
101 xrealloc (p, n)
102      VOID *p;
103      size_t n;
104 {
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;
111 }