xmalloc.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* xmalloc.c -- malloc with out of memory checking
  2. Copyright (C) 1990, 1991, 1993 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
  14. #ifdef HAVE_CONFIG_H
  15. #include <config.h>
  16. #endif
  17. #if __STDC__
  18. #define VOID void
  19. #else
  20. #define VOID char
  21. #endif
  22. #include <sys/types.h>
  23. #if STDC_HEADERS
  24. #include <stdlib.h>
  25. #else
  26. VOID *malloc ();
  27. VOID *realloc ();
  28. void free ();
  29. #endif
  30. #if __STDC__ && defined (HAVE_VPRINTF)
  31. void error (int, int, char const *, ...);
  32. #else
  33. void error ();
  34. #endif
  35. /* Allocate N bytes of memory dynamically, with error checking. */
  36. VOID *
  37. xmalloc (n)
  38. size_t n;
  39. {
  40. VOID *p;
  41. p = malloc (n);
  42. if (p == 0)
  43. /* Must exit with 2 for `cmp'. */
  44. error (2, 0, "memory exhausted");
  45. return p;
  46. }
  47. /* Change the size of an allocated block of memory P to N bytes,
  48. with error checking.
  49. If P is NULL, run xmalloc.
  50. If N is 0, run free and return NULL. */
  51. VOID *
  52. xrealloc (p, n)
  53. VOID *p;
  54. size_t n;
  55. {
  56. if (p == 0)
  57. return xmalloc (n);
  58. if (n == 0)
  59. {
  60. free (p);
  61. return 0;
  62. }
  63. p = realloc (p, n);
  64. if (p == 0)
  65. /* Must exit with 2 for `cmp'. */
  66. error (2, 0, "memory exhausted");
  67. return p;
  68. }