[Discuss] Casting the return value of malloc bad?

Andrew Resch andrewresch at gmail.com
Sat Jul 15 12:48:04 PDT 2006


On Sat, 2006-07-15 at 10:31 -0700, Adam Parkin wrote:
> Paul Nienaber wrote:
> > Do it this way:
> > 
> > foo = malloc(n * sizeof(*foo));
> > 
> > (the parentheses around *foo are unnecessary, but more readable, IMO)
> > 
> > ISO/ANSI/IEC C provides (since 1989) assignment between pointer-to-void
> > and other pointer types without the need for a cast.  The exception to
> > this is function pointers, which aren't required to be representable by
> > a pointer-to-void.  Of course, you're usually hard-pressed to find an
> > implementation that doesn't allow you to, and SUS/POSIX requires that
> > you can.
> > 
> > If you're wondering about sizeof(*foo), consider what happens if you
> > change the type of "foo" =)
> 
> Good point, but if the line immediately before the malloc looked like:
> 
> SomeType * foo = NULL;
> 
> then wouldn't sizeof (*foo) choke (NULL pointer dereference)?

Why would you be redeclaring the variable?



More information about the Discuss mailing list