Malloc problems

Badri Lokanathan badri at valhalla.ee.rochester.edu
Fri May 20 04:00:11 AEST 1988


In article <1988May17.184525.14461 at utzoo.uucp>, henry at utzoo.uucp (Henry Spencer) writes:
> 
> Definitely.  A good way to do this for garden-variety programs is to have
> a library function emalloc() which calls malloc, checks the result, and
> prints a message and exits if NULL.  This is *not* appropriate for use from

I have a set of utility definitions that are macros for doing exactly
these and more (such as swap, min/max) in a way that I think is quite
elegant. I also use macros for basic linked list handling (add_node,
delete_node etc.) by macros to avoid writing the same code again and again.

Say, for instance,
---------------------------- in file globals.c -------------------------
/* Contains globally visible variables. */
char memory_error[] = "Malloc ran out of memory.";
---------------------------- 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);		\
	}								\
}
---------------------------- in file your_own.c -------------------------
/* say I have to allocate an array of pointers to structures to bar. */
#include "utildefs.h"
struct foo {
	:
} **bar;
	:
	:
	MALLOC_N(bar,struct foo *,128);
	:
	:

-- 
"It's better to burn out               {) badri at valhalla.ee.rochester.edu
 Than it is to rust-                  //\\ {ames,cmcl2,columbia,cornell,
 But I'll corrode                    ///\\\ garp,harvard,ll-xn,rutgers}!
 Till I turn to dust."                _||_   rochester!ur-valhalla!badri



More information about the Comp.lang.c mailing list