[Discuss] Casting the return value of malloc bad?
Paul Nienaber
phox at phox.ca
Sun Jul 16 07:00:22 PDT 2006
Adam Parkin wrote:
>
> 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.
Moot point. If someone doesn't know what something that simple means,
they should stop poking at my code and finish learning C. The language
itself is something like 180 pages.
> 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.
Not really. You should intuitively think of "*foo" as "whatever foo
points to", which is what you want the sizeof, so to speak.
>
> 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.
But then you have to start using a typedef for all of your variables...
what if you shift precision of just ONE of the variables using the same
typedef? This sort-of forces you to use variable-specific typedefs to
future-proof your code, which is, of course, getting pretty fugly =)
~p
More information about the Discuss
mailing list