1 /* xmalloc.c - Do-or-die Memory management functions.
2 *
3 * Created by Kevin Locke (from numerous canonical examples)
4 *
5 * I hereby place this file in the public domain. It may be freely reproduced,
6 * distributed, used, modified, built upon, or otherwise employed by anyone
7 * for any purpose without restriction.
8 */
9
10 #include <stddef.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13
14 #ifndef EXIT_SUCCESS
15 #define EXIT_SUCCESS 0
16 #define EXIT_FAILURE 1
17 #endif
18
xmalloc(size_t size)19 void *xmalloc(size_t size)
20 {
21 void *allocated = malloc(size);
22
23 if (allocated == NULL) {
24 fprintf(stderr, "Error: Insufficient memory "
25 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
26 "(attempt to malloc %zu bytes)\n",
27 #else
28 "(attempt to malloc %u bytes)\n",
29 #endif
30 (unsigned int) size);
31 exit(EXIT_FAILURE);
32 }
33
34 return allocated;
35 }
36
xcalloc(size_t num,size_t size)37 void *xcalloc(size_t num, size_t size)
38 {
39 void *allocated = calloc(num, size);
40
41 if (allocated == NULL) {
42 fprintf(stderr, "Error: Insufficient memory "
43 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
44 "(attempt to calloc %zu bytes)\n",
45 #else
46 "(attempt to calloc %u bytes)\n",
47 #endif
48 (unsigned int) size);
49 exit(EXIT_FAILURE);
50 }
51
52 return allocated;
53 }
54
xrealloc(void * ptr,size_t size)55 void *xrealloc(void *ptr, size_t size)
56 {
57 void *allocated;
58
59 /* Protect against non-standard behavior */
60 if (ptr == NULL) {
61 allocated = malloc(size);
62 } else {
63 allocated = realloc(ptr, size);
64 }
65
66 if (allocated == NULL) {
67 fprintf(stderr, "Error: Insufficient memory "
68 # if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
69 "(attempt to realloc %zu bytes)\n",
70 #else
71 "(attempt to realloc %u bytes)\n",
72 #endif
73 (unsigned int) size);
74 exit(EXIT_FAILURE);
75 }
76
77 return allocated;
78 }
79