Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!shadooby!accuvax.nwu.edu!tank!ncar!ames!lll-winken!uunet!mcvax!hp4nl!ruuinf!piet From: piet@cs.ruu.nl (Piet van Oostrum) Newsgroups: comp.lang.c Subject: Re: malloc() and sizeof Message-ID: <1246@ruuinf.cs.ruu.nl> Date: 6 Apr 89 09:19:14 GMT References: <510@lakesys.UUCP> <9969@smoke.BRL.MIL> <624@gonzo.UUCP> Sender: piet@ruuinf.cs.ruu.nl Reply-To: piet@cs.ruu.nl (Piet van Oostrum) Organization: Dept of Computer Science, University of Utrecht, Holland Lines: 37 In-reply-to: daveb@gonzo.UUCP (Dave Brower) In article <624@gonzo.UUCP>, daveb@gonzo (Dave Brower) writes: `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. ` ` `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. The following example has a cast that is different from the type of the variable: typedef ..... FOO; FOO buf [BUFSIZ]; FOO *bufcopy; .... bufcopy = (FOO *) malloc (sizeof (buf)); bcopy (bufcopy, buf, sizeof (buf)); Of course you can use sizeof (FOO[BUFSIZ]), but why would you. It is much cleaner (IMHO) to use sizeof buf. This esample won't happen very often in practice, I think, but it is better to use a single programming style. -- Piet van Oostrum, Dept of Computer Science, University of Utrecht Padualaan 14, P.O. Box 80.089, 3508 TB Utrecht, The Netherlands Telephone: +31-30-531806. piet@cs.ruu.nl (mcvax!hp4nl!ruuinf!piet)