malloc() and sizeof

Richard Sargent richard at pantor.UUCP
Wed Apr 5 00:28:47 AEST 1989


> Received: by pantor.UUCP (UUL1.3#5109)
> 	from uunet with UUCP; Tue, 4 Apr 89 03:29:06 est
> Path: uunet!lll-winken!ames!haven!adm!smoke!gwyn
> From: gwyn at smoke.BRL.MIL (Doug Gwyn )
> Newsgroups: comp.lang.c
> Subject: Re: malloc() and sizeof
> Message-ID: <9969 at smoke.BRL.MIL>
> Date: 3 Apr 89 19:11:08 GMT
> References: <510 at lakesys.UUCP>
> Reply-To: gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>)
> Organization: Ballistic Research Lab (BRL), APG, MD.
> Lines: 14
> 
> 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.
> 
> sizeof comes in two flavors, sizeof(type) and sizeof object.  In the
> latter case the object-expression is not evaluated, only its type is
> used.  Therefore the above usage is perfectly legitimate.  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..


There is a very valid reason why one uses sizeof(object) rather than 
sizeof(type):  no matter what happens to the declaration of the object
during the software's lifetime, sizeof(object) will always remain
correct.  It is very easy to see where sizeof(type) requires dependency
changes in code: for example

        int   count;
        ...
        ... fread( ... sizeof(int) ... );

If the data structure were changed to a long, then maintainers MUST
go to the trouble of analysing the entire program to ensure that
any type dependencies are changed too.  This can be a very expensive
proposition for software development companies.

Yes, this is the voice of experience.  I have been burned this way.

I will close by agreeing that there are always going to be circumstances
where one form makes better sense than the other.  You just have to
figure out which case is which.

Richard Sargent
Systems Analyst



More information about the Comp.lang.c mailing list