1 /*
2 * alloc.c -- Useful allocation function/defintions
3 *
4 * Copyright (C)1999-2006 Mark Simpson <damned@world.std.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you can either send email to this
18 * program's maintainer or write to: The Free Software Foundation,
19 * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.
20 *
21 */
22 #ifdef HAVE_CONFIG_H
23 # include "config.h"
24 #endif /* HAVE_CONFIG_H */
25
26 #include "common.h"
27 #include "alloc.h"
28
29 static size_t alloc_limit = 0;
30
31 void
set_alloc_limit(size_t size)32 set_alloc_limit (size_t size)
33 {
34 alloc_limit = size;
35 }
36
37 size_t
get_alloc_limit()38 get_alloc_limit()
39 {
40 return alloc_limit;
41 }
42
43 static void
alloc_limit_failure(char * fn_name,size_t size)44 alloc_limit_failure (char *fn_name, size_t size)
45 {
46 fprintf (stderr,
47 "%s: Maximum allocation size exceeded "
48 "(maxsize = %lu; size = %lu).\n",
49 fn_name,
50 (unsigned long)alloc_limit,
51 (unsigned long)size);
52 }
53
54 void
alloc_limit_assert(char * fn_name,size_t size)55 alloc_limit_assert (char *fn_name, size_t size)
56 {
57 if (alloc_limit && size > alloc_limit)
58 {
59 alloc_limit_failure (fn_name, size);
60 exit (-1);
61 }
62 }
63
64 /* attempts to malloc memory, if fails print error and call abort */
65 void*
xmalloc(size_t size)66 xmalloc (size_t size)
67 {
68 void *ptr = malloc (size);
69 if (!ptr
70 && (size != 0)) /* some libc don't like size == 0 */
71 {
72 perror ("xmalloc: Memory allocation failure");
73 abort();
74 }
75 return ptr;
76 }
77
78 /* Allocates memory but only up to a limit */
79 void*
checked_xmalloc(size_t size)80 checked_xmalloc (size_t size)
81 {
82 alloc_limit_assert ("checked_xmalloc", size);
83 return xmalloc (size);
84 }
85
86 /* xmallocs memory and clears it out */
87 void*
xcalloc(size_t num,size_t size)88 xcalloc (size_t num, size_t size)
89 {
90 void *ptr = malloc(num * size);
91 if (ptr)
92 {
93 memset (ptr, '\0', (num * size));
94 }
95 return ptr;
96 }
97
98 /* xcallocs memory but only up to a limit */
99 void*
checked_xcalloc(size_t num,size_t size)100 checked_xcalloc (size_t num, size_t size)
101 {
102 alloc_limit_assert ("checked_xcalloc", (num *size));
103 return xcalloc (num, size);
104 }
105
106
107
108