Casting return of malloc

Discussion in 'C Programming' started by ytrama@gmail.com, Feb 8, 2005.

  1. Guest

    Hi,
    I have read in one of old posting that don't cast of pointer which
    is returned by the malloc. I would like to know the reason.

    Thanks in advance,
    YTR
     
    , Feb 8, 2005
    #1
    1. Advertising

  2. In article <>,
    <> wrote:
    >Hi,
    > I have read in one of old posting that don't cast of pointer which
    >is returned by the malloc. I would like to know the reason.


    It isn't necessary, and it hides errors. Why do the extra typing for
    something with a negative benefit?


    dave

    --
    Dave Vandervies
    Having said that, you tend to be a lot less wrong than most people (which
    might be why we take such an unholy delight in trying to find errors in
    what you write). --Richard Heathfield in comp.lang.c
     
    Dave Vandervies, Feb 8, 2005
    #2
    1. Advertising

  3. <> scribbled the following:
    > Hi,
    > I have read in one of old posting that don't cast of pointer which
    > is returned by the malloc. I would like to know the reason.


    It won't fix anything, but it may make the compiler think problems are
    fixed when they really aren't.

    Longer explanation:
    Without a proper prototype for malloc(), the compiler thinks it returns
    int. Thus, when malloc creates a void* value and returns it, the
    compiler implicitly converts it to int. The value is *already* broken at
    this case, so no amount of casting it to anything will help. However,
    if you cast it to a pointer type, the compiler will *think* you know
    what you're doing, and omit a warning. Thus you get broken code that
    looks like working code.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-------------------------------------------------------- rules! --------/
    "We sorcerers don't like to eat our words, so to say."
    - Sparrowhawk
     
    Joona I Palaste, Feb 8, 2005
    #3
  4. Joona I Palaste wrote:

    > ytrama wrote:
    >
    >>I have read in one old posting that
    >>[you shouldn't] cast [the] pointer which is returned by malloc.
    >>I would like to know the reason.

    >
    > It won't fix anything
    > but it may make the compiler think problems are fixed
    > when they really aren't.
    >
    > Longer explanation:
    > Without a proper prototype for malloc(),
    > the compiler thinks it returns int.
    > Thus, when malloc creates a void* value and returns it,
    > the compiler implicitly converts it to int.
    > The value is *already* broken at this case,
    > so no amount of casting it to anything will help.
    > However, if you cast it to a pointer type,
    > the compiler will *think* you know what you're doing and omit a warning.
    > Thus you get broken code that looks like working code.


    That's *not* true.

    > cat f.c

    void f(void) {
    char* p = (char*)malloc(128);
    for (size_t j = 0; j < 128; ++j)
    p[j] = j;
    }

    > gcc -Wall -std=c99 -pedantic -c f.c

    f.c: In function `f':
    f.c:2: warning: implicit declaration of function `malloc'
    f.c:3: error: `size_t' undeclared (first use in this function)
    f.c:3: error: (Each undeclared identifier is reported only once
    f.c:3: error: for each function it appears in.)
    f.c:3: error: parse error before "j"
    f.c:3: error: `j' undeclared (first use in this function)
    f.c:3: error: parse error before ')' token
    f.c: At top level:
    f.c:2: warning: unused variable `p'

    The compiler gives ample diagnostics
    should you fail to #include <stdlib.h>
    which defines malloc(size_t) and size_t.

    On good reason for casting malloc(int) to the desired type
    is so you can compile with a C++ compiler:

    > cat f.cc

    #include <stdlib.h>

    void f(void) {
    char* p = malloc(128);
    for (size_t j = 0; j < 128; ++j)
    p[j] = j;
    }

    > g++ -Wall -ansi -pedantic -c f.cc

    f.cc: In function `void f()':
    f.cc:4: error: invalid conversion from `void*' to `char*'
     
    E. Robert Tisdale, Feb 8, 2005
    #4
  5. Ben Pfaff Guest

    "" <> writes:

    > I have read in one of old posting that don't cast of pointer which
    > is returned by the malloc. I would like to know the reason.


    I don't recommend casting the return value of malloc():

    * The cast is not required in ANSI C.

    * Casting its return value can mask a failure to #include
    <stdlib.h>, which leads to undefined behavior.

    * If you cast to the wrong type by accident, odd failures can
    result.

    Some others do disagree, such as P.J. Plauger (see article
    <9sFIb.9066$>).

    --
    "This is a wonderful answer.
    It's off-topic, it's incorrect, and it doesn't answer the question."
    --Richard Heathfield
     
    Ben Pfaff, Feb 8, 2005
    #5
  6. CBFalconer Guest

    Ben Pfaff wrote:
    > "" <> writes:
    >
    >> I have read in one of old posting that don't cast of pointer which
    >> is returned by the malloc. I would like to know the reason.

    >
    > I don't recommend casting the return value of malloc():
    >
    > * The cast is not required in ANSI C.
    >
    > * Casting its return value can mask a failure to #include
    > <stdlib.h>, which leads to undefined behavior.
    >
    > * If you cast to the wrong type by accident, odd failures
    > can result.
    >
    > Some others do disagree, such as P.J. Plauger (see article
    > <9sFIb.9066$>).


    and E. Robert Trollsdale. What a combination! It reminds me of
    the first term in the process of summing an arithmetic progression,
    i.e. (1 + N) + (2 + N-1) ...

    --
    "If you want to post a followup via groups.google.com, don't use
    the broken "Reply" link at the bottom of the article. Click on
    "show options" at the top of the article, then click on the
    "Reply" at the bottom of the article headers." - Keith Thompson
     
    CBFalconer, Feb 8, 2005
    #6
  7. Flash Gordon Guest

    E. Robert Tisdale wrote:
    > Joona I Palaste wrote:
    >
    >> ytrama wrote:
    >>
    >>> I have read in one old posting that
    >>> [you shouldn't] cast [the] pointer which is returned by malloc.
    >>> I would like to know the reason.

    >>
    >>
    >> It won't fix anything
    >> but it may make the compiler think problems are fixed
    >> when they really aren't.
    >>
    >> Longer explanation:
    >> Without a proper prototype for malloc(),
    >> the compiler thinks it returns int.
    >> Thus, when malloc creates a void* value and returns it,
    >> the compiler implicitly converts it to int. The value is *already*
    >> broken at this case, so no amount of casting it to anything will help.
    >> However, if you cast it to a pointer type,
    >> the compiler will *think* you know what you're doing and omit a warning.
    >> Thus you get broken code that looks like working code.

    >
    > That's *not* true.
    >
    > > cat f.c

    > void f(void) {
    > char* p = (char*)malloc(128);
    > for (size_t j = 0; j < 128; ++j)
    > p[j] = j;
    > }
    >
    > > gcc -Wall -std=c99 -pedantic -c f.c

    > f.c: In function `f':


    <snip>

    > The compiler gives ample diagnostics
    > should you fail to #include <stdlib.h>
    > which defines malloc(size_t) and size_t.


    There are more compilers than are dreamed of in your philosophy.

    Or to be more explicit, why rely on the fact that *some* compilers will
    warn when by doing less typing you can ensure that *all* C compilers
    will produce a diagnostic.

    > On good reason for casting malloc(int) to the desired type
    > is so you can compile with a C++ compiler:


    Not a valid reason (except for whatsisname, sorry, I can't remember it)
    who has a commercial reason.

    The best way to integrate C code with any other language is to compile
    it as C and use whatever mechanism the other language provides for the
    integration. If you can point me at any C++ compiler vendor who does not
    also provide a C compiler that its code will link against I might
    reconsider, but such would be extremely rare.
    --
    Flash Gordon
    Living in interesting times.
    Although my email address says spam, it is real and I read it.
     
    Flash Gordon, Feb 8, 2005
    #7
  8. Ben Pfaff wrote:

    > I don't recommend casting the return value of malloc():
    >
    > Some others do disagree, such as P.J. Plauger
    > (see article <9sFIb.9066$>).


    Did you really mean to post an email address here?
     
    E. Robert Tisdale, Feb 8, 2005
    #8
  9. Mike Wahler Guest

    <> wrote in message
    news:...
    > Hi,
    > I have read in one of old posting that don't cast of pointer which
    > is returned by the malloc. I would like to know the reason.


    You've got it backwards. Before writing any cast,
    find a defensible reason to do so. There is no
    such reason when assigning a 'void*' (which is
    the type returned by 'malloc()') value to another
    (object) pointer type.

    -Mike
     
    Mike Wahler, Feb 8, 2005
    #9
  10. Ben Pfaff <> writes:
    > "" <> writes:
    >
    >> I have read in one of old posting that don't cast of pointer which
    >> is returned by the malloc. I would like to know the reason.

    >
    > I don't recommend casting the return value of malloc():
    >
    > * The cast is not required in ANSI C.
    >
    > * Casting its return value can mask a failure to #include
    > <stdlib.h>, which leads to undefined behavior.


    Some C90 compilers, and all conforming C99 compilers, will warn about
    this anyway. (That's certainly not an argument in favor of casting,
    of course.)

    > * If you cast to the wrong type by accident, odd failures can
    > result.
    >
    > Some others do disagree, such as P.J. Plauger (see article
    > <9sFIb.9066$>).


    I don't know that he necessarily disagrees; he just happens to work in
    an unusual environment where casting the result of malloc() makes
    sense. I don't think he would argue that *everyone* should cast the
    result of malloc(). (I can't find that message-id on Google; are you
    sure it's correct?)

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
     
    Keith Thompson, Feb 8, 2005
    #10
  11. E. Robert Tisdale, Feb 8, 2005
    #11
  12. Ben Pfaff Guest

    Keith Thompson <> writes:

    > Ben Pfaff <> writes:
    >> "" <> writes:
    >>
    >>> I have read in one of old posting that don't cast of pointer which
    >>> is returned by the malloc. I would like to know the reason.

    >>
    >> I don't recommend casting the return value of malloc():
    >>
    >> * The cast is not required in ANSI C.
    >>
    >> * Casting its return value can mask a failure to #include
    >> <stdlib.h>, which leads to undefined behavior.

    >
    > Some C90 compilers, and all conforming C99 compilers, will warn about
    > this anyway. (That's certainly not an argument in favor of casting,
    > of course.)


    Often I give this advice to novices, who in many cases seem to
    believe that the proper way to deal with warnings is to disable
    them. Experts, of course, know better, but experts are not in
    need of advice from me.

    >> * If you cast to the wrong type by accident, odd failures can
    >> result.
    >>
    >> Some others do disagree, such as P.J. Plauger (see article
    >> <9sFIb.9066$>).

    >
    > I don't know that he necessarily disagrees; he just happens to work in
    > an unusual environment where casting the result of malloc() makes
    > sense. I don't think he would argue that *everyone* should cast the
    > result of malloc().


    I think you're right. I will rephrase my advice for future
    posts. How about this:

    In unusual circumstances it may make sense to cast the return
    value of malloc(). P. J. Plauger, for example, has good
    reasons to want his code to compile as both C and C++,
    and C++ requires the cast. However, Plauger's case is rare
    indeed. Most programmers should write their code as either C
    or C++, not in the intersection of the two.

    > (I can't find that message-id on Google; are you sure it's
    > correct?)


    I can't be sure, if it's not available now, but I cut-and-paste
    it instead of trying to retype it, so I don't know what would
    have gone wrong.
    --
    "A lesson for us all: Even in trivia there are traps."
    --Eric Sosman
     
    Ben Pfaff, Feb 8, 2005
    #12
  13. Michael Mair Guest

    E. Robert Tisdale wrote:
    > Joona I Palaste wrote:
    >
    >> ytrama wrote:
    >>
    >>> I have read in one old posting that
    >>> [you shouldn't] cast [the] pointer which is returned by malloc.
    >>> I would like to know the reason.

    >>
    >>
    >> It won't fix anything
    >> but it may make the compiler think problems are fixed
    >> when they really aren't.
    >>
    >> Longer explanation:
    >> Without a proper prototype for malloc(),
    >> the compiler thinks it returns int.
    >> Thus, when malloc creates a void* value and returns it,
    >> the compiler implicitly converts it to int. The value is *already*
    >> broken at this case, so no amount of casting it to anything will help.
    >> However, if you cast it to a pointer type,
    >> the compiler will *think* you know what you're doing and omit a warning.
    >> Thus you get broken code that looks like working code.

    >
    >
    > That's *not* true.
    >
    > > cat f.c

    use of size_t without <stdio.h> or <stdlib.h> requires
    #include <stddef.h>

    Your example is broken.

    > void f(void) {
    > char* p = (char*)malloc(128);
    > for (size_t j = 0; j < 128; ++j)
    > p[j] = j;
    > }
    >
    > > gcc -Wall -std=c99 -pedantic -c f.c

    > f.c: In function `f':
    > f.c:2: warning: implicit declaration of function `malloc'
    > f.c:3: error: `size_t' undeclared (first use in this function)
    > f.c:3: error: (Each undeclared identifier is reported only once
    > f.c:3: error: for each function it appears in.)
    > f.c:3: error: parse error before "j"
    > f.c:3: error: `j' undeclared (first use in this function)
    > f.c:3: error: parse error before ')' token
    > f.c: At top level:
    > f.c:2: warning: unused variable `p'
    >
    > The compiler gives ample diagnostics
    > should you fail to #include <stdlib.h>
    > which defines malloc(size_t) and size_t.


    All of your errors and one warning come from your failure to #include
    <stddef.h>, only one warning from the use of malloc() without prototype
    in scope. Many people unfortunately ignore warnings.


    > On good reason for casting malloc(int) to the desired type
    > is so you can compile with a C++ compiler:


    [snip]

    This is comp.lang.c; C++ compilers cannot compile many
    standard conforming C programs as C and C++ are different
    languages.
    Apart from a select few exceptions, mixing of C and C++
    is unnecessary and unnecessarily dangerous. C++ specified
    an interface to C for a very good reason.


    -Michael
    --
    E-Mail: Mine is an /at/ gmx /dot/ de address.
     
    Michael Mair, Feb 8, 2005
    #13
  14. Michael Mair wrote:

    > This is comp.lang.c;
    > C++ compilers cannot compile many standard conforming C programs


    C++ compiler can compile *most* standard conforming C programs.

    > as C and C++ are different languages.


    C++ contains almost all of C.

    > Apart from a select few exceptions,
    > mixing of C and C++ is unnecessary and unnecessarily dangerous.


    Who said anything about "mixing" C and C++?
    When I compile C programs with my C++ compiler, they *are* C++ programs.

    > C++ specified an interface to C for a very good reason.


    C++ does *not* specify an interface to C.
    It specifies extern "C" to *help* with linkage.
    The C++ compiler must be compatible with the C compiler
    which might be accomplished
    if, for example, the C++ compiler conforms with
    the C Application Binary Interface (ABI)
    for the target platform.
     
    E. Robert Tisdale, Feb 8, 2005
    #14
  15. E. Robert Tisdale wrote:
    > Ben Pfaff wrote:
    >>Some others do disagree, such as P.J. Plauger
    >>(see article <9sFIb.9066$>).

    >
    > Did you really mean to post an email address here?


    That's no email address. It's a message ID. To be specific it's the
    message id of the following message:

    http://groups.google.com/groups?selm=9sFIb.9066$&rnum=1

    --
    If geiger counter does not click,
    the coffee, she is just not thick
     
    Sebastian Hungerecker, Feb 8, 2005
    #15
  16. Sebastian Hungerecker <> scribbled the following:
    > E. Robert Tisdale wrote:
    >> Ben Pfaff wrote:
    >>>Some others do disagree, such as P.J. Plauger
    >>>(see article <9sFIb.9066$>).

    >>
    >> Did you really mean to post an email address here?


    > That's no email address. It's a message ID. To be specific it's the
    > message id of the following message:


    > http://groups.google.com/groups?selm=9sFIb.9066$&rnum=1


    Frankly, I believe Trollsdale knew that. I don't think anyone would be
    stupid enough to think a string of text with something so unreadable
    (even including a $ sign, no less) before the "@" sign was an e-mail
    address, even though the mere sight of the "@" sign screams "e-mail
    address!!!" to 99.999% of the world's literate population.
    It's just that Trollsdale is being Trollsdale again. He pretends to be
    stupider than he really is, hoping it will annoy people.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-------------------------------------------------------- rules! --------/
    "We're women. We've got double standards to live up to."
    - Ally McBeal
     
    Joona I Palaste, Feb 8, 2005
    #16
  17. Joona I Palaste wrote:

    > He pretends to be stupider than he really is,


    I'm not pretending. ;-)

    I'm as stupid as I appear to be.

    But I'd like to believe that you are pretending.
     
    E. Robert Tisdale, Feb 8, 2005
    #17
  18. infobahn Guest

    "E. Robert Tisdale" wrote:
    >
    > Michael Mair wrote:
    >
    > > This is comp.lang.c;
    > > C++ compilers cannot compile many standard conforming C programs

    >
    > C++ compiler can compile *most* standard conforming C programs.


    It generally fails to compile mine.

    > > as C and C++ are different languages.

    >
    > C++ contains almost all of C.


    Not enough. More to the point, too much extra.

    > > Apart from a select few exceptions,
    > > mixing of C and C++ is unnecessary and unnecessarily dangerous.

    >
    > Who said anything about "mixing" C and C++?
    > When I compile C programs with my C++ compiler, they *are* C++ programs.


    Then please feel free to discuss them in comp.lang.c++


    <snip>
     
    infobahn, Feb 8, 2005
    #18
  19. In article <cuarf5$caq$>,
    E. Robert Tisdale <> wrote:

    >On good reason for casting malloc(int) to the desired type
    >is so you can compile with a C++ compiler:


    And if you do this:

    #define BEGIN {
    #define END }
    #define IF if(
    #define THEN )

    you can write even worse code that you can compile with a Pascal
    compiler too!

    (Wait, you've suggested doing this before, haven't you? Forget I said
    anything...)


    dave

    --
    Dave Vandervies
    Would you perchance feel like compiling Java in your C++ compiler? ... from
    my understanding of the languages in question you could probably hack up a
    program which is valid Java and compiles as C++. --Ian Woods in CLC
     
    Dave Vandervies, Feb 9, 2005
    #19
  20. Randy Howard Guest

    In article <cub6v5$ib3$>,
    says...
    > I'm as stupid as I appear to be.


    You are being far too modest.

    --
    Randy Howard (2reply remove FOOBAR)
    "Making it hard to do stupid things often makes it hard
    to do smart ones too." -- Andrew Koenig
     
    Randy Howard, Feb 9, 2005
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John
    Replies:
    13
    Views:
    710
  2. ravi
    Replies:
    0
    Views:
    457
  3. Peter
    Replies:
    34
    Views:
    1,969
    Richard Tobin
    Oct 22, 2004
  4. Tinkertim

    Casting the return value of malloc() ?

    Tinkertim, Oct 2, 2008, in forum: C Programming
    Replies:
    82
    Views:
    2,259
    David Thompson
    Oct 20, 2008
  5. Gene
    Replies:
    0
    Views:
    449
Loading...

Share This Page