Fix memory leaks.
[pspp-builds.git] / src / alloc.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    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, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "alloc.h"
22 #include "error.h"
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include "str.h"
26 \f
27 /* Public functions. */
28
29 /* Allocates a block of SIZE bytes and returns it.
30    If SIZE is 0, returns a null pointer.
31    Aborts if unsuccessful. */
32 void *
33 xmalloc (size_t size)
34 {
35   void *vp;
36   if (size == 0)
37     return NULL;
38
39   vp = malloc (size);
40   if (!vp)
41     out_of_memory ();
42
43   return vp;
44 }
45
46 /* Allocates a block of SIZE bytes, fill it with all-bits-0, and
47    returns it.
48    If SIZE is 0, returns a null pointer.
49    Aborts if unsuccessful. */
50 void *
51 xcalloc (size_t size)
52 {
53   void *vp = xmalloc (size);
54   memset (vp, 0, size);
55   return vp;
56 }
57
58 /* If SIZE is 0, then block PTR is freed and a null pointer is
59    returned.
60    Otherwise, if PTR is a null pointer, then a new block is allocated
61    and returned.
62    Otherwise, block PTR is reallocated to be SIZE bytes in size and
63    the new location of the block is returned.
64    Aborts if unsuccessful. */
65 void *
66 xrealloc (void *ptr, size_t size)
67 {
68   void *vp;
69   if (!size)
70     {
71       if (ptr)
72         free (ptr);
73
74       return NULL;
75     }
76
77   if (ptr)
78     vp = realloc (ptr, size);
79   else
80     vp = malloc (size);
81
82   if (!vp)
83     out_of_memory ();
84
85   return vp;
86 }
87
88 /* Makes a copy of string S in malloc()'d memory and returns the copy.
89    S must not be a null pointer. */
90 char *
91 xstrdup (const char *s)
92 {
93   size_t size;
94   char *t;
95
96   assert (s != NULL);
97
98   size = strlen (s) + 1;
99
100   t = malloc (size);
101   if (!t)
102     out_of_memory ();
103
104   memcpy (t, s, size);
105   return t;
106 }
107
108 /* Report an out-of-memory condition and abort execution. */
109 void
110 out_of_memory (void)
111 {
112   fprintf (stderr, "virtual memory exhausted\n");
113   exit (EXIT_FAILURE);
114 }