[Discuss] Casting the return value of malloc bad?
Paul Nienaber
phox at phox.ca
Sat Jul 15 08:43:49 PDT 2006
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" =)
~p
Andrew Resch wrote:
> This link seems to explain it:
> http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1047673478&id=1043284351
>
>
> Basically, there is no need and it will just cause problems if you
> decide to
> change the type of pointer.
>
> On 7/11/06, Adam Parkin <pzelnip at telus.net> wrote:
>>
>> Okay a question for the C gurus on the list: I've heard from a few
>> people that casting the return value from malloc is bad practice, is
>> this true, and if so, why? And more importantly, if it is bad practice,
>> then what is a better practice (and why)?
>>
>> --
>> Adam Parkin
>> E-mail: pzelnip at telus.net
>> ----------------------
>> To an optimist the glass is half-full.
>> To a pessimist the glass is half-empty.
>> To a computer scientist the glass is twice as big as it needs to be.
>>
>> _______________________________________________
>> Discuss mailing list
>> Discuss at vlug.org
>> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss
>>
> _______________________________________________
> Discuss mailing list
> Discuss at vlug.org
> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss
>
More information about the Discuss
mailing list