1 /*
2 * MEMEXTRA.C
3 *
4 * Written 1995-1996 by Andrew Clarke and released to the public domain.
5 *
6 * Memory allocation routines with core exhaust checking.
7 */
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include "memextra.h"
13
14 static char msg_alloc_fail[] =
15 "*** Memory allocation failure (out of memory)\n"
16 "*** Needed %u (%Xh) bytes.\n";
17
18 static char msg_realloc_fail[] =
19 "*** Memory reallocation failure (out of memory)\n"
20 "*** Needed %u (%Xh) bytes.\n";
21
22 static char msg_free_fail[] =
23 "*** Memory deallocation failure (attempted to free null pointer)\n";
24
25 extern void cleanup(char *, ...);
26
xmalloc(size_t size)27 void *xmalloc(size_t size)
28 {
29 void *ptr;
30 ptr = malloc(size);
31 if (ptr == NULL)
32 {
33 cleanup(msg_alloc_fail, (unsigned)size, (unsigned)size);
34 exit(0);
35 }
36 return ptr;
37 }
38
xcalloc(size_t nmemb,size_t size)39 void *xcalloc(size_t nmemb, size_t size)
40 {
41 void *ptr;
42 ptr = calloc(nmemb, size);
43 if (ptr == NULL)
44 {
45 cleanup(msg_alloc_fail, (unsigned)(nmemb * size), (unsigned)(nmemb * size));
46 exit(0);
47 }
48 return ptr;
49 }
50
xrealloc(void * ptr,size_t size)51 void *xrealloc(void *ptr, size_t size)
52 {
53 if (ptr == NULL)
54 {
55 return xmalloc(size);
56 }
57 if (size == (size_t) 0)
58 {
59 xfree(ptr);
60 return NULL;
61 }
62 ptr = realloc(ptr, size);
63 if (ptr == NULL)
64 {
65 cleanup(msg_realloc_fail, (unsigned)size, (unsigned)size);
66 exit(0);
67 }
68 return ptr;
69 }
70
xstrdup(const char * str)71 char *xstrdup(const char *str)
72 {
73 if (str == NULL)
74 {
75 return NULL;
76 }
77 return strcpy(xmalloc(strlen(str) + 1), str);
78 }
79
xfree(void * ptr)80 void xfree(void *ptr)
81 {
82 if (ptr == NULL)
83 {
84 cleanup(msg_free_fail);
85 exit(0);
86 }
87 else
88 {
89 free(ptr);
90 }
91 }
92
93 #ifdef OS2
94 #include "malloc16.h"
95
xfree16(void * ptr)96 void xfree16(void *ptr)
97 {
98 if (ptr == NULL)
99 {
100 cleanup(msg_free_fail);
101 exit(0);
102 }
103 else
104 {
105 free16(ptr);
106 }
107 }
108
xmalloc16(size_t size)109 void *xmalloc16(size_t size)
110 {
111 void *ptr;
112 ptr = malloc16(size);
113 if (ptr == NULL)
114 {
115 cleanup(msg_alloc_fail, (unsigned)size, (unsigned)size);
116 exit(0);
117 }
118 return ptr;
119 }
120 #endif
121