Malloc problems
T. William Wells
bill at proxftl.UUCP
Sun May 29 10:16:00 AEST 1988
In article <1313 at valhalla.ee.rochester.edu>, badri at valhalla.ee.rochester.edu (Badri Lokanathan) writes:
> ---------------------------- in file utildefs.h -------------------------
> extern char *malloc();
> extern char memory_error[];
> #define MALLOC_N(A,B,N) { \
> if ((A=(B *) malloc((unsigned) (N)*sizeof(B))) == NULL) { \
> (void) fputs(memory_error,stderr); exit(-666); \
> } \
> }
Try, instead, this:
#include <stdlib.h>
extern void *Malloc_tmp; /* Define this with malloc_fail. */
extern void *malloc_fail(size_t N);
#define MALLOC(B,N) ((Malloc_tmp = malloc((size_t)(N) * sizeof(B))) \
? (B *)Malloc_tmp \
: (B *)malloc_fail((size_t)(N) * sizeof(B)))
If you do not have an ANSI-ish C compiler:
#define size_t unsigned
extern void *malloc();
extern void *Malloc_tmp; /* Define this with malloc_fail. */
extern void *malloc_fail(size_t N);
#define MALLOC(B,N) ((Malloc_tmp = malloc((size_t)((N) * sizeof(B)))) \
? (B *)Malloc_tmp \
: (B *)malloc_fail((size_t)((N) * sizeof(B))))
If your compiler does not have void *, use char *.
This has several advantages.
o The generated code is smaller.
o All details of the error handling are hidden.
o It can be used in an expression.
o Malloc_fail could do other things, like purge memory and retry the
allocation.
More information about the Comp.lang.c
mailing list