Why not cast malloc? 
Author Message
 Why not cast malloc?

I've read in a few threads here people saying that you shouldn't cast malloc's
return in C.  Why is this?  I almost always cast, and never had a problem.  I
find it makes it easier for me to remember just what it was I was allocating
memory for.

Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in the
FAQ?) :)

--

AndrewJ

AIM ID xLuminous
ICQ #62467370



Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?


Quote:
> I've read in a few threads here people saying that you shouldn't cast
malloc's
> return in C.  Why is this?  I almost always cast, and never had a
problem.  I
> find it makes it easier for me to remember just what it was I was
allocating
> memory for.

We write code either because it has a positive benefit or because it
prevents something bad happening.

In C, casting doesn't prevent anything bad happening. For char *p,

p = malloc(1000);

and

p = (char *)malloc(1000);

are equivalent - the cast doesn't do anything wonderful that we need in
order to be able to use the memory. So it has no positive benefit, and it
doesn't prevent anything bad happening. So why put it in?

Now consider what happens if you have unaccountably forgotten to #include
<stdlib.h>.

The line

p = malloc(1000);

will give you a diagnostic, because the compiler will have assumed, in the
absence of any other information, that malloc returns int, but here you are
trying to assign it as if it were a pointer.

The line

p = (char *)malloc(1000);

may well /not/ give you a diagnostic. The cast assures the compiler that
all is well. You are, effectively, saying to the compiler "yes I know
malloc returns int, but - for reasons which make perfect sense to me but
which it's impossible to explain to you - I want to pretend it's a char *.
I know exactly what I'm doing, so trust me, it'll be fine".

The compiler is now free to generate code on the assumption that malloc
returns int. Consider a system where sizeof(void *) == 8 but sizeof(int) ==
2. The compiler may store the result of the malloc call in a 16-bit
register rather than a 64-bit register. The consequences to your code could
be unfortunate.

In this case, then, casting gives you no benefits, prevents no problems,
gives you /more typing/ to do, and potentially conceals a serious bug. So
why do it?

Quote:
> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it
in the
> FAQ?) :)

I trust this answer is elaborate enough for you. If not, let me know - I
have some oak veneer somewhere... ;-)

--
Richard Heathfield

"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.

comp.lang.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html



Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?
Andrew Jones a crit dans le message ...

Quote:
>I've read in a few threads here people saying that you shouldn't cast
malloc's
>return in C.  Why is this?  I almost always cast, and never had a problem.
I
>find it makes it easier for me to remember just what it was I was
allocating
>memory for.

Look at this thread "Can't free memory any advice?"

I have given a response to this question, that have been kindly amended by
Lawrence Kirby.

-hs- 2000/02/13 08:32

Quote:
>Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in
the
>FAQ?) :)

A begining of answer is here
http://www.eskimo.com/~scs/C-faq/q7.7.html

--
-hs-
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC



Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?


Quote:
> I've read in a few threads here people saying that you shouldn't cast
malloc's
> return in C.  Why is this?  I almost always cast, and never had a problem.
I
> find it makes it easier for me to remember just what it was I was
allocating
> memory for.

The NOMINATIVE you give the assignment SPECIFIES what it's allocated within
completely.  Perhaps this is your deficiency.

Quote:
> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in
the
> FAQ?) :)

It's NOT a no-no.  It's merely not NECESSARY.  Karl M


Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

>> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in
>the
>> FAQ?) :)

>It's NOT a no-no.  It's merely not NECESSARY.  Karl M

        Seems to me that it would implicitly cast it anyway, so why not?

        char *mystring;

        mystring = malloc(sizeof(char)*10);

        Since mystring is of type (char *), it's going to implicitly cast it anyway,
yes?

        Mike

--

--------------------------------------
There are many things in life that will catch your eye,
but only a few that will catch your heart...pursue those.
                -- Anonymous



Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

wrote in comp.lang.c:

Quote:

> >> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in
> >the
> >> FAQ?) :)

> >It's NOT a no-no.  It's merely not NECESSARY.  Karl M

>    Seems to me that it would implicitly cast it anyway, so why not?

>    char *mystring;

>    mystring = malloc(sizeof(char)*10);

>    Since mystring is of type (char *), it's going to implicitly cast it anyway,
> yes?

>    Mike

Not exactly cast, but automatically convert which is not quite the
same thing.

Since we're here, though...

sizeof(char) is 1 by definition in C (and C++ for that matter), and it
_always_ will be because it would break half of the existing C code
ever written if it changes.

So it is never necessary, and nothing is ever gained, by multiplying
by sizeof(char).

To quote from Richard's post earlier in this thread:

Quote:
> We write code either because it has a positive benefit or because it
> prevents something bad happening.

Multiplying by sizeof(char) doesn't meet either of these tests.

What can prevent something bad from happening is this:

some_pointer = malloc(10 * sizeof *some_pointer);

This happens to result multiplying by sizeof(char) if some_pointer is
defined as a pointer to char, but can really save the day if the
original programmer or some maintenance programmer changes
some_pointer from BIG_STRUCT * to EVEN_BIGGER_STRUCT *.

Jack Klein
--
Home: http://jackklein.home.att.net



Thu, 01 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

>sizeof(char) is 1 by definition in C (and C++ for that matter), and it
>_always_ will be because it would break half of the existing C code
>ever written if it changes.

        Hey, I just like to be consistent. I figure the compiler will optimize this
to a 1 anyway, so while to you, nothing is gained, nothing is lost either. I
however, gain readability by remembering specifically when I look at it that I
wanted characters.
        To each their own.

        Mike

--

--------------------------------------
There are many things in life that will catch your eye,
but only a few that will catch your heart...pursue those.
                -- Anonymous



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?


Quote:

>>> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in
>>the
>>> FAQ?) :)

>>It's NOT a no-no.  It's merely not NECESSARY.  Karl M

>        Seems to me that it would implicitly cast it anyway, so why not?

The term is "converted". A cast is a syntactic operator in C and is always
explicit.

Quote:
>        char *mystring;

>        mystring = malloc(sizeof(char)*10);

>        Since mystring is of type (char *), it's going to implicitly cast it
> anyway,
>yes?

By putting a cast in explicitly you do two things

1. reduce error checking on the compatibility between the source and
   target types (because casts support more type combinations than
   implicit conversions). In the case of malloc() this means that you
   lose a required diagnostic (at least prior to C99) when malloc()
   is called without being properly declared.

2. Make the code less flexible and more difficult to maintain by forcing
   a particular target type.

Similar to 2 is that you make tyhe code less flexible and more difficult to
maintain if you put explicit type information in the size calculation.
If you write it like this

         mystring = malloc(10 * sizeof *mystring);

then it will allocate the correct amount of memory for 10 elements whatever
type mystring has (with some minor exceptions that will generally alert
you with diagnostics). With this form you need look no further to see
that it is correct. When you start putting explicit type information in
you have to cross-reference against the type of mystring which makes it
inherently less readable and also more prone to error.

--
-----------------------------------------


-----------------------------------------



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

> I've read in a few threads here people saying that you shouldn't cast malloc's
> return in C.  Why is this?  I almost always cast, and never had a problem.  I
> find it makes it easier for me to remember just what it was I was allocating
> memory for.

> Anyone care to elaborate on why it seems to be such a no-no?  (Or is it in the
> FAQ?) :)

Yes, this is a FAQ.  Couldn't you bother looking?  

--

What one knows is, in youth, of little moment; they know enough who
know how to learn. - Henry Adams

A thick skin is a gift from God. - Konrad Adenauer
__________________________________________________________
Fight spam now!
Get your free anti-spam service: http://www.brightmail.com



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

> So it is never necessary, and nothing is ever gained, by multiplying
> by sizeof(char).
> To quote from Richard's post earlier in this thread:
>> We write code either because it has a positive benefit or because it
>> prevents something bad happening.
> Multiplying by sizeof(char) doesn't meet either of these tests.

So in char's I see your point, but there's no harm in it.  The
major benefit in using the sizeof() is whatif you have something
like this:

double *foo;

if ((foo = malloc(10 * sizeof(foo)) == NULL)
        /* handle null case */

/* do stuff */

IMO, this is the best way to use sizeof, because if foo was
declared global 1000+ lines up somewhere, and you allofthesudden
wanted to change foo to a float, then you just need to change
one line rather than more than one.

-Mike (pink)

--

moon really, as a matter of fact, | 1312 Senior RecTA
its all dark. -Roger Waters       | && ProgDev



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

> double *foo;
> if ((foo = malloc(10 * sizeof(foo)) == NULL)
>    /* handle null case */
> /* do stuff */
> IMO, this is the best way to use sizeof, because if foo was

if ((foo = malloc(10 * sizeof *foo) == NULL)
                              ^

IMO this is an even better use ;)

--
              /"\                              m i k e    b u r r e l l

               X        AGAINST HTML MAIL      http://mikpos.dyndns.org
              / \



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?


Quote:



> >>> Anyone care to elaborate on why it seems to be such a no-no?  (Or is
it in
> >>the
> >>> FAQ?) :)

> >>It's NOT a no-no.  It's merely not NECESSARY.  Karl M

> >        Seems to me that it would implicitly cast it anyway, so why not?

> The term is "converted". A cast is a syntactic operator in C and is always
> explicit.

> >        char *mystring;

> >        mystring = malloc(sizeof(char)*10);

> >        Since mystring is of type (char *), it's going to implicitly cast
it
> > anyway,
> >yes?

> By putting a cast in explicitly you do two things

> 1. reduce error checking on the compatibility between the source and
>    target types (because casts support more type combinations than
>    implicit conversions). In the case of malloc() this means that you
>    lose a required diagnostic (at least prior to C99) when malloc()
>    is called without being properly declared.

> 2. Make the code less flexible and more difficult to maintain by forcing
>    a particular target type.

> Similar to 2 is that you make tyhe code less flexible and more difficult
to
> maintain if you put explicit type information in the size calculation.
> If you write it like this

>          mystring = malloc(10 * sizeof *mystring);

> then it will allocate the correct amount of memory for 10 elements
whatever
> type mystring has (with some minor exceptions that will generally alert
> you with diagnostics). With this form you need look no further to see
> that it is correct. When you start putting explicit type information in
> you have to cross-reference against the type of mystring which makes it
> inherently less readable and also more prone to error.

You're looking at the ASSIGNMENT as a THING-IN-ITSELF.  Your description is
just NEGATED Hungarian notation, or a solution in search of a short-cut.
The problem is MUCH bigger.  Karl M


Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

> You're looking at the ASSIGNMENT as a THING-IN-ITSELF.  Your description is
> just NEGATED Hungarian notation, or a solution in search of a short-cut.
> The problem is MUCH bigger.  Karl M

The Problem

   Casting calls to the malloc() functions are liable to cover
up diagnostics that would be normally printed out (at least
diagnostics pertaining to stdlib.h and its lack of inclusion) and
cause problems with systems where a pointer is a different size
than an int.  Since malloc() is not prototyped, the compiler
would assume that malloc() is some function that returns an
integer, which may or may not be the same size as a pointer.  The
result of this problem is that you may end up with a program that
accesses the wrong address.

The Solution

   Include <stdlib.h> to prototype malloc().

   As to your previous two sentences, you're on your own.




Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

> You're looking at the ASSIGNMENT as a THING-IN-ITSELF.

Why do I get the feeling that if I were to ask karl to define
"THING-IN-ITSELF", he would respond by telling my I've mistaken his use
of it as a THING-IN-ITSELF?

I.

--
 ____
|    | Ian R. Hay <http://www3.sympatico.ca/ian.hay/>



Fri, 02 Aug 2002 03:00:00 GMT  
 Why not cast malloc?

Quote:

>> > You're looking at the ASSIGNMENT as a THING-IN-ITSELF.

>> Why do I get the feeling that if I were to ask karl to define
>> "THING-IN-ITSELF", he would respond by telling my I've mistaken his use
>> of it as a THING-IN-ITSELF?
> THING-IN-ITSELF as opposed to THING-FOR-ITSELF.  Purely OBJECTIVE as opposed
> to purely SUBJECTIVE -- taking something out of ITS context and removing its
> STATUS.

   Is there any reason you capitalize random words in your
sentences?

Quote:
> To claim that casting the result of the malloc function will
>>  Make the code less flexible and more difficult to maintain by forcing
>>    a particular target type.
> ignores the NOMINATIVE's status.  It's (the LVALUE is) ALREADY typed before
> the ASSIGNMENT.  There's NOTHING to force.

   Right, as long as you actually prototype malloc() to take care
of the problems I brought up in a previous post on this thread.




Sat, 03 Aug 2002 03:00:00 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Why not cast the rerurn from malloc()?

2. malloc: to cast or not to cast

3. Why cast malloc's return?

4. why not typecast malloc() o/p??????

5. Linked List -- why not just "malloc()"?

6. Q: Why IMalloc not malloc or HeapAlloc?

7. to cast or not to cast?

8. Discarded Function Values (To Cast or Not to Cast)

9. When is a cast not a cast?

10. to malloc() or not to malloc(), that is the question

11. casting malloc question.

12. casting malloc question.

 

 
Powered by phpBB® Forum Software