1 /* Copyright (C) 2000-2012 by George Williams */
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are met:
6 * Redistributions of source code must retain the above copyright notice, this
7 * list of conditions and the following disclaimer.
9 * Redistributions in binary form must reproduce the above copyright notice,
10 * this list of conditions and the following disclaimer in the documentation
11 * and/or other materials provided with the distribution.
13 * The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 /* wrappers around standard memory routines so we can trap errors. */
33 static void default_trap(void) {
34 fprintf(stderr
, "Attempt to allocate memory failed.\n" );
38 static void (*trap
)(void) = default_trap
;
40 void galloc_set_trap(void (*newtrap
)(void)) {
41 if ( newtrap
==NULL
) newtrap
= default_trap
;
46 void *galloc(long size
) {
48 /* Avoid malloc(0) as malloc is allowed to return NULL.
49 * If malloc fails, call trap() to allow it to possibly
50 * recover memory and try again.
52 while (( ret
= malloc(size
==0 ? sizeof(int) : size
))==NULL
)
54 memset(ret
,0x3c,size
); /* fill with random junk for debugging */
58 void *gcalloc(int cnt
,long size
) {
60 while (( ret
= calloc(cnt
,size
))==NULL
)
65 void *grealloc(void *old
,long size
) {
67 while (( ret
= realloc(old
,size
))==NULL
)
72 void gfree(void *old
) {
75 #endif /* USE_OUR_MEMORY */
77 void NoMoreMemMessage(void) {
78 /* Output an 'Out of memory' message, then continue */
79 fprintf(stderr
, "Out of memory\n" );
82 char *copy(const char *str
) {
87 ret
= (char *) galloc(strlen(str
)+1);
92 char *copyn(const char *str
,long n
) {
97 ret
= (char *) galloc(n
+1);