[Discuss] Casting the return value of malloc bad?

Adam Parkin pzelnip at telus.net
Sun Jul 16 05:53:01 PDT 2006


Paul Nienaber wrote:
> It doesn't matter if it's pointing to anything.  sizeof is
> compile-time.  It's an operator, not a function, and the value of the
> expression you feed it is irrelevant.

Duh, right, I always get caught thinking sizeof is a function not an 
operator because it's token is a word and not 1 or 2 funny characters 
(that, and I always enclose it's operand in parentheses).  =8-p  Thanks 
for the tip.

> I'm going to *strongly* disagree with putting the type of the variable
> in your code more than once.  Use foo = malloc(n * sizeof(*foo));,
> seriously, and encourage other people to use it.  Then you *can't* screw
> up changing foo's type.  And no, there's no dereference.  *foo is simply
> ......
> crap you do in beginner CSC courses) typically involves assigning to a
> (pointer) variable at some point OTHER than where it is declared, and
> therefore the use of the variable to determine the size of the type it
> points to is REALLY, REALLY valuable in making your code easier to maintain.

Okay I see that, but it still seems a bit academic.  So long as foo's 
type is specified with a typedef, then I don't see how there's any more 
difficulty in maintaining the code than if you use your method.  OTOH 
you could argue that your method is less common and thus will tend to be 
more confusing for other programmers.  You could also argue that the 
type in the malloc is more readable as

malloc (sizeof(SomeType))

is closer to the meaning of what you're trying to express (give me 
enough bytes to hold a SomeType).  The difference is more clear when 
using malloc to allocate an array:

foo = malloc (sizeof(SomeType) * 5)

Which looks like you're saying "foo is an array of 5 SomeType's" which 
is exactly right, but:

foo = malloc (sizeof(*foo) * 5)

looks like you're saying "foo is an array of 5 foo's" which I suppose 
isn't not right (pardon the double-negative), but certainly the former 
looks closer to the meaning of what you're trying to express.

Don't get me wrong, I like your method and will probably start using it 
in things I write, I just don't think it makes a huge difference either 
way.  As long as there is only one point where foo's type is specified, 
it seems to me you're fine.
-- 
--
Adam Parkin
E-mail: pzelnip at telus.net
----------------------
"Honesty is the best policy" is not an economic doctrine.

	-- Kenneth Lux, "Adam Smith's Mistake"


More information about the Discuss mailing list