1/* xmalloc.c -- malloc with out of memory checking 2 Copyright (C) 1990, 91, 92, 93, 94 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ 17 18#ifdef 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 33VOID *calloc (); 34VOID *malloc (); 35VOID *realloc (); 36void free (); 37#endif 38 39//#include <libintl.h> 40 41#define _(str) gettext (str) 42 43#ifndef EXIT_FAILURE 44#define EXIT_FAILURE 4 45#endif 46 47/* Exit value when the requested amount of memory is not available. 48 The caller may set it to some other value. */ 49int xmalloc_exit_failure = EXIT_FAILURE; 50 51#if __STDC__ && (HAVE_VPRINTF || HAVE_DOPRNT) 52void error (int, int, const char *, ...); 53#else 54void error (); 55#endif 56 57static VOID * 58fixup_null_alloc (n) 59 size_t n; 60{ 61 VOID *p; 62 63 p = 0; 64 if (n == 0) 65 p = malloc ((size_t) 1); 66 if (p == 0) 67 error (xmalloc_exit_failure, 0, _("memory exhausted")); 68 return p; 69} 70 71/* Allocate N bytes of memory dynamically, with error checking. */ 72 73VOID * 74xmalloc (n) 75 size_t n; 76{ 77 VOID *p; 78 79 p = malloc (n); 80 if (p == 0) 81 p = fixup_null_alloc (n); 82 return p; 83} 84 85/* Allocate memory for N elements of S bytes, with error checking. */ 86 87VOID * 88xcalloc (n, s) 89 size_t n, s; 90{ 91 VOID *p; 92 93 p = calloc (n, s); 94 if (p == 0) 95 p = fixup_null_alloc (n); 96 return p; 97} 98 99/* Change the size of an allocated block of memory P to N bytes, 100 with error checking. 101 If P is NULL, run xmalloc. */ 102 103VOID * 104xrealloc (p, n) 105 VOID *p; 106 size_t n; 107{ 108 if (p == 0) 109 return xmalloc (n); 110 p = realloc (p, n); 111 if (p == 0) 112 p = fixup_null_alloc (n); 113 return p; 114} 115