Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!pantor!richard From: richard@pantor.UUCP (Richard Sargent) Newsgroups: comp.lang.c Subject: Re: malloc() and sizeof Message-ID: <3.UUL1.3#5109@pantor.UUCP> Date: 4 Apr 89 14:28:47 GMT References: <9969@smoke.BRL.MIL> Organization: Pansophic Systems Inc, Graphics Product Company Lines: 52 > 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@smoke.BRL.MIL (Doug Gwyn ) > Newsgroups: comp.lang.c > Subject: Re: malloc() and sizeof > Message-ID: <9969@smoke.BRL.MIL> > Date: 3 Apr 89 19:11:08 GMT > References: <510@lakesys.UUCP> > Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) > Organization: Ballistic Research Lab (BRL), APG, MD. > Lines: 14 > > In article <510@lakesys.UUCP> chad@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