Re: why is casting malloc a bad thing?

From: Sidney Cadot (sidney_at_jigsaw.nl)
Date: 01/30/04


Date: Fri, 30 Jan 2004 18:52:32 +0100

Dan Pop wrote:

>> [...]
>>If you don't use the appropriate command line options to enable such
>>warnings, that's more of a problem than casting malloc results can ever be.
>>
>>In short, I think this argument is stale, and is getting staler all the
>>time.

> Try a reality check: how many newbies have you seen enabling such
> warnings when they show the way they compiled their code (quite often,
> people posting here show their compilation command line)?

All too many, for sure. I wouldn't necessarily recommend malloc casting
to newbies. I wouldn't recommend C to newbies, for that matter.

> And keep in mind that this discussion is focused on newbies, experienced
> programmers have already defined their preference pro or con casting
> void pointers and it is not this thread that is going to make them change
> their minds (you will keep casting when this discussion is over, I will
> keep avoiding such casts as the plague).

I agree on this for most part, except that this shows a level of
subtlety on this issue that does not rhyme well with the kind of
reactions that code samples with malloc casts invariably evokes
around here.

Best regards,

   Sidney



Relevant Pages

  • Re: Casting return of malloc
    ... Not casting malloc can also mask undefined behaviour, ... "FWIW, I would advise most C programmers *not* to cast malloc calls, ... "1) Style rules should be developed by considering all applicable ...
    (comp.lang.c)
  • Re: bivariate interpolation
    ... Which is one of the reasons for my rewrite. ... time following the thread about casting malloc() calls. ... > be horrible but it should compile (BTW did you test the routine spat out by ...
    (comp.lang.c)
  • Re: How does free() knows?
    ... See the FAQ section 7.7. ... > implicit casting is better than explict casting? ... malloc() returns a void pointer and that gets automatically ... An explicit cast will keep the compiler from complaining (even ...
    (comp.lang.c)
  • Re: what will happen after i use free()???
    ... you almost certainly won't be using malloc anyway.) ... since otherwise you won't be alerted by the compiler if you ... - except you likes to land in the world of undefined behavior. ... Functionally, no, but see previous comment (i.e. not casting is not ...
    (comp.lang.c)
  • Re: malloc and free
    ... In the past I have always been casting the malloc. ... > of the allocated block the pointer is pointing to. ... I get a lot of overhead in the operating system. ...
    (comp.lang.c)