[Discuss] Casting the return value of malloc bad?
Andrew Resch
andrewresch at gmail.com
Sat Jul 15 12:49:09 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)?
OH sorry about the last email.. I should read before replying.
The sizeof(*foo) will return the size of SomeType, not the length of
data that it is pointing to.
More information about the Discuss
mailing list