[comp.lang.c] less redundant way to use malloc

throopw@dg_rtp.UUCP (Wayne Throop) (05/05/87)

> tps@sdchem.UUCP (Tom Stockfisch)
>> greg@utcsri.UUCP (Gregory Smith)
>>> edw@ius2.cs.cmu.edu (Eddie Wyatt)

>>>>#define alloc(type)		((type *) malloc(sizeof(type)))
>>...problem...is that (type *) is not always a
>>cast to pointer to type: e.g.  int (*)() means pointer to func returning int,
>>but ( int (*)() * ) means you get a syntax error.
>>There is no cure for this; it is a result of C's bass-ackward type syntax.
> There is a workaround, but you might not like it:
> # define palloc( ptype )	(  (ptype)malloc( sizeof( *(ptype) ) )  )
> now to get a 
> 	int	(*)()
> you must do
> 	palloc( int (**)() )

I assume you mean
        
        #define palloc( ptype ) ((ptype)malloc( sizeof( *((ptype)0) )))

which ought to work.  The version without the zero seems go give a
syntax error when I try it.

This has some additional problems, in that one can't easily allocate
arrays of things pointed to by the pointer type argument, but a separate
macro with a scale factor will fix that up.  Alternatively, one could
allocate the type (*)[N], though it has the limitation that N must be
known at compile-time.

The other weakness of this scheme is, of course, that one is taking
sizeof(*((sometype *)0)).  As nearly as I can tell, this ought to be
legal, according to K&R, H&S, and draft X3J11.  But I wouldn't be
surprised if some overzealous compiler decided to slap your hands for it
and refuse to compile it.  Sigh.

--
Another interesting facet of ninja was the use of magic. They had
a reputation as sorcerors and wizards who could fly and hypnotize, and
walk through walls, and get away with huge deductions on their taxes.
                --- Bruce Israel martial-arts-request@brillig
-- 
Wayne Throop      <the-known-world>!mcnc!rti!dg_rtp!throopw