malloc() and sizeof

Dave Brower daveb at gonzo.UUCP
Wed Apr 5 16:04:36 AEST 1989


In <9969 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>In article <510 at lakesys.UUCP> chad at lakesys.UUCP (Chad Gibbons) writes:
>>The style I have seen used recently around here has been this:
>>	struct foo tmp = (struct foo *)malloc(sizeof *tmp);
>>compiled and worked fine...however, this seems to be a poor programming
>>practice at best, and a shoestring at worse.
>
>...  As to
>whether it is better or worse than the alternative style, there
>don't seem to be really strong arguments on either side.  I personally
>prefer sizeof(type) since to me the other form is just a corruption of
>this fundamental definition, but I'm sure other programmers disagree.
>It doesn't seem to be worth arguing about.

Of course I disagree, or I wouldn't post :-).  And I think I can make an
argument that is at least partly convincing from a software engineering
or reliability perspective.

In the trivial example shown, it really doesn't make any difference. 
However, the real case is quite often:

	struct foo *tmp;

	/* tons-o-code deleted */

	tmp  = (struct foo *)malloc( /*your choice here*/ );

It is all too easy to forget the type of "tmp" at this point.  If you do
your malloc argument as sizeof(*tmp), you cannot go wrong.  Further, if
you change the type of the definition of tmp above, you will not need to
change the argument to sizeof.

Compare this to the use of manifest constants.  If you can define
something in one place, you are stylistically better off.  Since C can't
verify that the arg to the malloc sizeof is the right type, better to
not need to define it multiple places either.

Of course, this argument bogs down when you realize you already needed
to know the type to get the cast on the malloc return correct.  But
given the choice, I'd still rather only have to get the type right once
(in the cast) rather than in the cast _and_ the sizeof.  (And it takes
less space if you have vars named "tmp" or "p" :-).

-dB

PS,

So my bias shows, I'm also in the minority that prefers

	if( CONST == var )

to let the compiler check that I didn't do

	if( CONST = var )
	
by mistake.  Some of my co-workers truly revile this style quirk.

-- 
"I came here for an argument." "Oh.  This is getting hit on the head"
{sun,mtxinu,amdahl,hoptoad}!rtech!gonzo!daveb	daveb at gonzo.uucp



More information about the Comp.lang.c mailing list