Path: utzoo!utgpu!water!watmath!clyde!bellcore!rutgers!tut.cis.ohio-state.edu!mandrill!gatech!uflorida!novavax!proxftl!bill
From: bill@proxftl.UUCP (T. William Wells)
Newsgroups: comp.lang.c
Subject: Re: Malloc problems
Summary: suggestion for improvement
Message-ID: <232@proxftl.UUCP>
Date: 29 May 88 00:16:00 GMT
References: <272@marob.MASA.COM> <690008@hpfelg.HP.COM>, <1313@valhalla.ee.rochester.edu>
Organization: Proximity Technology, Ft. Lauderdale
Lines: 39

In article <1313@valhalla.ee.rochester.edu>, badri@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 
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.