Path: utzoo!attcan!uunet!lll-winken!lll-lcc!ames!ll-xn!mit-eddie!bbn!rochester!ur-tut!ur-valhalla!badri From: badri@valhalla.ee.rochester.edu (Badri Lokanathan) Newsgroups: comp.lang.c Subject: Re: Malloc problems Summary: Abuse the preprocessor instead :-) Message-ID: <1313@valhalla.ee.rochester.edu> Date: 19 May 88 18:00:11 GMT References: <272@marob.MASA.COM> <690008@hpfelg.HP.COM>, <1988May17.184525.14461@utzoo.uucp> Organization: UR Dept. of Electrical Engg, Rochester NY 14627 Lines: 39 In article <1988May17.184525.14461@utzoo.uucp>, henry@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@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