1 /*
2 * xmalloc.c
3 * Copyright (C) 1998-2005 A.J. van Os
4 *
5 * Description:
6 * Extended malloc and friends
7 */
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include "antiword.h"
12
13 static char *szMessage =
14 "Memory allocation failed, unable to continue";
15 #if defined(__dos) && !defined(__DJGPP__)
16 static char *szDosMessage =
17 "DOS can't allocate this kind of memory, unable to continue";
18 #endif /* __dos && !__DJGPP__ */
19
20
21 /*
22 * xmalloc - Allocates dynamic memory
23 *
24 * See malloc(3), but unlike malloc(3) xmalloc does not return in case
25 * of error.
26 */
27 void *
xmalloc(size_t tSize)28 xmalloc(size_t tSize)
29 {
30 void *pvTmp;
31
32 TRACE_MSG("xmalloc");
33
34 if (tSize == 0) {
35 tSize = 1;
36 }
37 pvTmp = malloc(tSize);
38 if (pvTmp == NULL) {
39 DBG_MSG("xmalloc returned NULL");
40 DBG_DEC(tSize);
41 werr(1, szMessage);
42 }
43 return pvTmp;
44 } /* end of xmalloc */
45
46 /*
47 * xcalloc - Allocates and zeros dynamic memory
48 *
49 * See calloc(3), but unlike calloc(3) xcalloc does not return in case of error
50 */
51 void *
xcalloc(size_t tNmemb,size_t tSize)52 xcalloc(size_t tNmemb, size_t tSize)
53 {
54 void *pvTmp;
55
56 TRACE_MSG("xcalloc");
57
58 #if defined(__dos) && !defined(__DJGPP__)
59 if ((ULONG)tNmemb * (ULONG)tSize > 0xffffUL) {
60 DBG_DEC((ULONG)tNmemb * (ULONG)tSize);
61 werr(1, szDosMessage);
62 }
63 #endif /* __dos && !__DJGPP__ */
64
65 if (tNmemb == 0 || tSize == 0) {
66 tNmemb = 1;
67 tSize = 1;
68 }
69 pvTmp = calloc(tNmemb, tSize);
70 if (pvTmp == NULL) {
71 DBG_MSG("xcalloc returned NULL");
72 werr(1, szMessage);
73 }
74 return pvTmp;
75 } /* end of xcalloc */
76
77 /*
78 * xrealloc - Changes the size of a memory object
79 *
80 * See realloc(3), but unlike realloc(3) xrealloc does not return in case
81 * of error.
82 */
83 void *
xrealloc(void * pvArg,size_t tSize)84 xrealloc(void *pvArg, size_t tSize)
85 {
86 void *pvTmp;
87
88 TRACE_MSG("xrealloc");
89
90 pvTmp = realloc(pvArg, tSize);
91 if (pvTmp == NULL) {
92 DBG_MSG("realloc returned NULL");
93 werr(1, szMessage);
94 }
95 return pvTmp;
96 } /* end of xrealloc */
97
98 /*
99 * xstrdup - Duplicate a string
100 *
101 * See strdup(3), but unlike strdup(3) xstrdup does not return in case
102 * of error.
103 *
104 * NOTE:
105 * Does not use strdup(3), because some systems don't have it.
106 */
107 char *
xstrdup(const char * szArg)108 xstrdup(const char *szArg)
109 {
110 char *szTmp;
111
112 TRACE_MSG("xstrdup");
113
114 szTmp = xmalloc(strlen(szArg) + 1);
115 strcpy(szTmp, szArg);
116 return szTmp;
117 } /* end of xstrdup */
118
119 /*
120 * xfree - Deallocates dynamic memory
121 *
122 * See free(3).
123 *
124 * returns NULL;
125 * This makes p=xfree(p) possible, free memory and overwrite the pointer to it.
126 */
127 void *
xfree(void * pvArg)128 xfree(void *pvArg)
129 {
130 TRACE_MSG("xfree");
131
132 if (pvArg != NULL) {
133 free(pvArg);
134 }
135 return NULL;
136 } /* end of xfree */
137