malloc() and sizeof
Piet van Oostrum
piet at cs.ruu.nl
Thu Apr 6 19:19:14 AEST 1989
In article <624 at gonzo.UUCP>, daveb at 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 at cs.ruu.nl (mcvax!hp4nl!ruuinf!piet)
More information about the Comp.lang.c
mailing list