Re: malloc + 4??

From: Keith Thompson (kst-u_at_mib.org)
Date: 04/05/04


Date: Mon, 05 Apr 2004 09:30:12 GMT


"Kevin Torr" <kevintorr@hotmail.com> writes:
> "Chris Torek" <nospam@torek.net> wrote in message
> news:c4pdra031ga@news2.newsguy.com...
[...]
> Wow, thanks for all that. I will have to get my head around it all.
>
> So when do I need not cast mallocs? when I include a header? which header?
> Or are you saying that I don't need to cast a malloc if I've already defined
> the pointer as a data type?
> What would be a possible bad thing if I did cast a malloc when I didn't need
> to? Is there something that could go wrong or is it just redundant?

Speaking of redundant, you just re-posted over 230 lines of Chris
Torek's text. Please limit quoted material to what's relevant to your
reply.

To answer your question, if you're going to use malloc() you should
always include <stdlib.h>, and you should never cast the result.

Casting the result masks possible errors. It can eliminate the
warning message you'll get if you've forgotten to include <stdlib.h>,
but only because you're lying to the compiler. It's like eliminating
a warning light on your dashboard by unscrewing the light bulb rather
than by fixing the problem it's trying to tell you about.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
San Diego Supercomputer Center             <*>  <http://users.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"


Relevant Pages

  • Re: problem with memcpy and pointers/arrays confusion - again
    ... this second method is known as an explicit conversion, or cast. ... The cast, in effect, tells the compiler: ... the malloc function. ... function taking a size_t as a parameter and returning a void pointer (i.e. ...
    (comp.lang.c)
  • Re: why is casting malloc a bad thing?
    ... In the compilers we used in the 1980s (including VAX ... compilers for IBM PCs), malloc() had type: ... Without the cast, you got ... and adds HUGE amounts of risk. ...
    (comp.lang.c)
  • Re: compiling on different compilers
    ... > Is my version an error or just not the recommended style? ... - casting the return value from malloc() may hide a bug if ... you a diagnostic if there is no cast. ... and more prone to error during maintenance. ...
    (comp.lang.c)
  • Re: Reading a string of unknown size
    ... "Don't cast return value of malloc() in C. ... It is entirely possible for an int to be returned by a ... function using a different method than that used to return a pointer. ...
    (comp.lang.c)
  • Re: Using malloc
    ... If compiling C code, ... however (and still using malloc versus new) will require you to do the ... the C language did not enjoy the void pointer. ... Because of this a cast was required: ...
    (alt.comp.lang.learn.c-cpp)