1 /* These are some dynamic memory allocation facilities. They are essentially
2 an extension to C, as they do allocations with a cognizance of C
3 variables. You can use them to make C read more like a high level
7 #ifndef MALLOCVAR_INCLUDED
8 #define MALLOCVAR_INCLUDED
13 static __inline__
void
14 mallocProduct(void ** const resultP
,
15 unsigned int const factor1
,
16 unsigned int const factor2
) {
17 /*----------------------------------------------------------------------------
18 malloc a space whose size in bytes is the product of 'factor1' and
19 'factor2'. But if that size cannot be represented as an unsigned int,
20 return NULL without allocating anything. Also return NULL if the malloc
23 Note that malloc() actually takes a size_t size argument, so the
24 proper test would be whether the size can be represented by size_t,
25 not unsigned int. But there is no reliable indication available to
26 us, like UINT_MAX, of what the limitations of size_t are. We
27 assume size_t is at least as expressive as unsigned int and that
28 nobody really needs to allocate more than 4GB of memory.
29 -----------------------------------------------------------------------------*/
30 if (UINT_MAX
/ factor2
< factor1
)
33 *resultP
= malloc(factor1
* factor2
);
38 static __inline__
void
39 reallocProduct(void ** const blockP
,
40 unsigned int const factor1
,
41 unsigned int const factor2
) {
43 if (UINT_MAX
/ factor2
< factor1
)
46 *blockP
= realloc(*blockP
, factor1
* factor2
);
51 #define MALLOCARRAY(arrayName, nElements) \
52 mallocProduct((void **)&arrayName, nElements, sizeof(arrayName[0]))
54 #define REALLOCARRAY(arrayName, nElements) \
55 reallocProduct((void **)&arrayName, nElements, sizeof(arrayName[0]))
58 #define MALLOCARRAY_NOFAIL(arrayName, nElements) \
60 MALLOCARRAY(arrayName, nElements); \
61 if ((arrayName) == NULL) \
65 #define REALLOCARRAY_NOFAIL(arrayName, nElements) \
67 REALLOCARRAY(arrayName, nElements); \
68 if ((arrayName) == NULL) \
73 #define MALLOCVAR(varName) \
74 varName = malloc(sizeof(*varName))
76 #define MALLOCVAR_NOFAIL(varName) \
77 do {if ((varName = malloc(sizeof(*varName))) == NULL) abort();} while(0)