Re: faq & casting malloc()

From: pete (pfiland_at_mindspring.com)
Date: 06/23/04


Date: Wed, 23 Jun 2004 11:40:42 GMT

tweak wrote:
 
> Note: The only item I can find regarding casting
> of malloc() is K&R2 pg. 142:

Check the errata:
http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

142(§6.5, toward the end): The remark about casting the return value
of malloc ("the proper method is to declare ... then
explicitly coerce") needs to be rewritten. The example is correct
and works, but the advice is debatable in the context of the
1988-1989 ANSI/ISO standards. It's not necessary
(given that coercion of void * to ALMOSTANYTYPE * is automatic),
and possibly harmful if malloc, or a proxy for it,
fails to be declared as returning void *.
The explicit cast can cover up an unintended error.
On the other hand, pre-ANSI, the cast was necessary,
and it is in C++ also.

-- 
pete


Relevant Pages

  • Re: C99 Question
    ... ("the proper method is to declare ... ... then explicitly coerce") ... fails to be declared as returning void *. ... The explicit cast can cover up an unintended error. ...
    (comp.lang.c)
  • Re: faq & casting malloc()
    ... The remark about casting the return value ... > explicitly coerce") needs to be rewritten. ... > The explicit cast can cover up an unintended error. ... I didn't know there was a errata from the book available since ...
    (comp.lang.c)
  • Re: How to read data ?
    ... then explicitly coerce") needs to be rewritten. ... and possibly harmful if malloc, or a proxy for it, ... fails to be declared as returning void *. ... The explicit cast ...
    (comp.lang.c)
  • Re: Scheme and libraries -- piggyback on Java?
    ... pointers to be assigned to other pointer types without casting. ... I suppose I did know at one time that void* was convertible without ... I also just realized that I haven't used an actual C compiler since ...
    (comp.lang.scheme)
  • Re: is const necessary in eg int compar(const void *, const void *)
    ... void *' arguments to assign to a temporary pointer of the appropriate ... avoid casting. ... except that a pointer may be assigned to a _Bool. ... int by_age(const void *vsl, const void *vsr) ...
    (comp.lang.c)