[Discuss] Casting the return value of malloc bad?

Adam Parkin pzelnip at telus.net
Sat Jul 15 10:31:27 PDT 2006


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)?
-- 
--
Adam Parkin
E-mail: pzelnip at telus.net
----------------------
Men are born ignorant, not stupid; they are made stupid by education.

	-- Bertrand Russell, http://www.vanderburg.org/Misc/Quotes/quotes.html


More information about the Discuss mailing list