Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!amdahl!rtech!gonzo!daveb From: daveb@gonzo.UUCP (Dave Brower) Newsgroups: comp.lang.c Subject: Re: malloc() and sizeof Message-ID: <624@gonzo.UUCP> Date: 5 Apr 89 06:04:36 GMT References: <510@lakesys.UUCP> <9969@smoke.BRL.MIL> Reply-To: daveb@gonzo.UUCP (Dave Brower) Organization: Gonzo Media Group Lines: 60 In <9969@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) writes: >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. > >... 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@gonzo.uucp