bce4325135e04ea46cb2d927747b2a8b11eaa9fa
[gnulib.git] / lib / xmalloc.c
1 /* xmalloc.c -- malloc with out of memory checking
2    Copyright (C) 1990, 1991, 1993 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 #if 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 #if __STDC__ && defined (HAVE_VPRINTF)
39 void error (int, int, char const *, ...);
40 #else
41 void error ();
42 #endif
43
44 /* Allocate N bytes of memory dynamically, with error checking.  */
45
46 VOID *
47 xmalloc (n)
48      size_t n;
49 {
50   VOID *p;
51
52   p = malloc (n);
53   if (p == 0)
54     /* Must exit with 2 for `cmp'.  */
55     error (2, 0, "virtual memory exhausted");
56   return p;
57 }
58
59 /* Change the size of an allocated block of memory P to N bytes,
60    with error checking.
61    If P is NULL, run xmalloc.
62    If N is 0, run free and return NULL.  */
63
64 VOID *
65 xrealloc (p, n)
66      VOID *p;
67      size_t n;
68 {
69   if (p == 0)
70     return xmalloc (n);
71   if (n == 0)
72     {
73       free (p);
74       return 0;
75     }
76   p = realloc (p, n);
77   if (p == 0)
78     /* Must exit with 2 for `cmp'.  */
79     error (2, 0, "virtual memory exhausted");
80   return p;
81 }