malloc() and sizeof

Chris Torek chris at mimsy.UUCP
Tue Apr 4 00:11:42 AEST 1989


In article <510 at lakesys.UUCP> chad at lakesys.UUCP (Chad Gibbons) writes:
>	I have seen a somewhat strange style of coding a malloc() call on
>some systems.  Usually, given struct foo, you would execute the call such
>as this:
>
>	struct foo tmp = (struct foo *)malloc(sizeof(struct foo));

No: rather, `struct foo *tmp = <as above>'

>The style I have seen used recently around here has been this:
>
>	struct foo tmp = (struct foo *)malloc(sizeof *tmp);

Perfectly legal (given `struct foo *tmp' rather than `struct foo
tmp').  The argument to sizeof is examined only to find its type; any
compiler that actually tries to find `*tmp' during program execution
has a severe bug (one on the order of computing 1|2 as -1 instead of 3,
or 1||2 as -1 instead of 1).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list