[comp.unix.wizards] my stupid question about malloc

roy@phri.UUCP (Roy Smith) (11/10/87)

	In article <3015@phri.UUCP> I asked a stupid question about malloc,
and sort of accused Sun's malloc of having a bug.  Of course, the bug was
not in malloc, but in my own code, saying "xp = (x *) malloc (n)" instead
of "xp = (x *) malloc (n * sizeof (x))".

	I posted that question after a long frustrating day (why doesn't
lint catch these things:-)) and then went to watch the latest episode of
"Star Trek: The Next Generation" on TV.  By the time the show was over, I
figured out what the problem was and cancled the article.  Not soon enough,
it seems, by the number of replies I've gotten.
-- 
Roy Smith, {allegra,cmcl2,philabs}!phri!roy
System Administrator, Public Health Research Institute
455 First Avenue, New York, NY 10016

edw@IUS1.CS.CMU.EDU (Eddie Wyatt) (11/11/87)

> 
> 	In article <3015@phri.UUCP> I asked a stupid question about malloc,
> and sort of accused Sun's malloc of having a bug.  Of course, the bug was
> not in malloc, but in my own code, saying "xp = (x *) malloc (n)" instead
> of "xp = (x *) malloc (n * sizeof (x))".
> 
> 	I posted that question after a long frustrating day (why doesn't
> lint catch these things:-)) and then went to watch the latest episode of
> "Star Trek: The Next Generation" on TV.  By the time the show was over, I
> figured out what the problem was and cancled the article.  Not soon enough,
> it seems, by the number of replies I've gotten.


   This problem could have been avoided if you used macro definitions like:


extern char *malloc();
extern char *calloc();

#define NULLPTR(type)		((type *) 0)
#define alloc(type)		((type *) malloc(sizeof(type)))
#define alloc_array(type,size)	((type *) malloc(sizeof(type)* \
					((unsigned)(size))))
#define mfree(x)		 free((char *) x)

#define clear_alloc(type)	((type *) calloc((unsigned) 1,sizeof(type)))
#define clear_alloc_array(type,size)	((type *) calloc((unsigned) size, \
						sizeof(type)))

#define resize_array(ptr, type, size) ((type *) realloc((char *) ptr, \
                                        ((unsigned) (sizeof(type) *(size)))))


BTW: I don't want to hear how theses macros don't work on all data types.
     If you (the net community) don't like them, you don't have to use them.

Also has anyone  else noticed that posts have been bouncing around, like
some articles are appear 2 or 3 times in the same news group???



-- 
That one looks Jewish -- And that one's a coon -- Who let all this riff raff
into the room -- There's one smoking a joint -- and Anoter with spots -- If
I had my way -- I'd have all of you shot ... Pink Floyd, "In the Flesh"
Eddie Wyatt 				e-mail: edw@ius1.cs.cmu.edu