Imported from antiword-0.37.tar.gz.
[antiword.git] / xmalloc.c
blobb64bc44e547f0bae871af28d22b51625f79fbb6f
1 /*
2 * xmalloc.c
3 * Copyright (C) 1998-2005 A.J. van Os
5 * Description:
6 * Extended malloc and friends
7 */
9 #include <stdlib.h>
10 #include <string.h>
11 #include "antiword.h"
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__ */
22 * xmalloc - Allocates dynamic memory
24 * See malloc(3), but unlike malloc(3) xmalloc does not return in case
25 * of error.
27 void *
28 xmalloc(size_t tSize)
30 void *pvTmp;
32 TRACE_MSG("xmalloc");
34 if (tSize == 0) {
35 tSize = 1;
37 pvTmp = malloc(tSize);
38 if (pvTmp == NULL) {
39 DBG_MSG("xmalloc returned NULL");
40 DBG_DEC(tSize);
41 werr(1, szMessage);
43 return pvTmp;
44 } /* end of xmalloc */
47 * xcalloc - Allocates and zeros dynamic memory
49 * See calloc(3), but unlike calloc(3) xcalloc does not return in case of error
51 void *
52 xcalloc(size_t tNmemb, size_t tSize)
54 void *pvTmp;
56 TRACE_MSG("xcalloc");
58 #if defined(__dos) && !defined(__DJGPP__)
59 if ((ULONG)tNmemb * (ULONG)tSize > 0xffffUL) {
60 DBG_DEC((ULONG)tNmemb * (ULONG)tSize);
61 werr(1, szDosMessage);
63 #endif /* __dos && !__DJGPP__ */
65 if (tNmemb == 0 || tSize == 0) {
66 tNmemb = 1;
67 tSize = 1;
69 pvTmp = calloc(tNmemb, tSize);
70 if (pvTmp == NULL) {
71 DBG_MSG("xcalloc returned NULL");
72 werr(1, szMessage);
74 return pvTmp;
75 } /* end of xcalloc */
78 * xrealloc - Changes the size of a memory object
80 * See realloc(3), but unlike realloc(3) xrealloc does not return in case
81 * of error.
83 void *
84 xrealloc(void *pvArg, size_t tSize)
86 void *pvTmp;
88 TRACE_MSG("xrealloc");
90 pvTmp = realloc(pvArg, tSize);
91 if (pvTmp == NULL) {
92 DBG_MSG("realloc returned NULL");
93 werr(1, szMessage);
95 return pvTmp;
96 } /* end of xrealloc */
99 * xstrdup - Duplicate a string
101 * See strdup(3), but unlike strdup(3) xstrdup does not return in case
102 * of error.
104 * NOTE:
105 * Does not use strdup(3), because some systems don't have it.
107 char *
108 xstrdup(const char *szArg)
110 char *szTmp;
112 TRACE_MSG("xstrdup");
114 szTmp = xmalloc(strlen(szArg) + 1);
115 strcpy(szTmp, szArg);
116 return szTmp;
117 } /* end of xstrdup */
120 * xfree - Deallocates dynamic memory
122 * See free(3).
124 * returns NULL;
125 * This makes p=xfree(p) possible, free memory and overwrite the pointer to it.
127 void *
128 xfree(void *pvArg)
130 TRACE_MSG("xfree");
132 if (pvArg != NULL) {
133 free(pvArg);
135 return NULL;
136 } /* end of xfree */