casting return value from malloc 
Author Message
 casting return value from malloc

(Sorry if this message appears more than once... my news server is
acting weird.)

People here typically say that we should not cast the return value
from malloc() and related functions because it is unnecessary and can
mask problems the compiler would otherwise warn you about, such as
not including stdlib.h.

However, I can see several equally valid reasons for using the cast.
For one thing, *not* using the cast can *also* mask problems the
compiler would otherwise warn you about, such as malloc'ing space for
the wrong type.  If I write

  int* foo;
  foo = malloc(100 * sizeof(int));

and later change foo's type to long* without remembering to fix
malloc's argument, the compiler will not catch the error.  But the
compiler is required to issue a diagnostic for

  long* foo;
  foo = (int*) malloc(100 * sizeof(int));

Secondly, including the cast serves as a reminder to the programmer
of the type of object for which space is being allocated.  In this
respect it has the same role as good commenting or good variable
naming conventions.

Lastly, including the cast will make it easier to port the code to
C++ should this ever become necessary or desired.  It is not always
possible to program entirely in the common subset of C and C++, but
in this case little is lost by doing so.

These, combined with the fact that AFAIK most compilers will complain
about calling malloc without stdlib.h regardless of whether a cast is
present, make me wonder if the wisdom of not casting should be
reevaluated.  Perhaps at the very least it should be considered an
issue of personal coding style, similar in status to indentation size
or curly brace placement, rather than something for which posters to
comp.lang.c are regularly admonished.

What do the experts think?
--Steve



Mon, 07 Mar 2005 06:46:59 GMT  
 casting return value from malloc
Submitted by "Steve Kobes" to comp.lang.c:

Quote:
> (Sorry if this message appears more than once... my news server is
> acting weird.)

> People here typically say that we should not cast the return value
> from malloc() and related functions because it is unnecessary and can
> mask problems the compiler would otherwise warn you about, such as
> not including stdlib.h.

> However, I can see several equally valid reasons for using the cast.
> For one thing, *not* using the cast can *also* mask problems the
> compiler would otherwise warn you about, such as malloc'ing space for
> the wrong type.  If I write

>   int* foo;
>   foo = malloc(100 * sizeof(int));

> and later change foo's type to long* without remembering to fix
> malloc's argument, the compiler will not catch the error.  But the
> compiler is required to issue a diagnostic for

>   long* foo;
>   foo = (int*) malloc(100 * sizeof(int));

That's why you should write

foo = malloc(100 * sizeof *foo);

This way you're free to totally forget about the line containing
the call to malloc(), even if you change the type of 'foo'.

--
Andreas K?h?ri
--------------------------------------------------------------
Stable, secure, portable, free:     www.netbsd.org



Mon, 07 Mar 2005 07:02:01 GMT  
 casting return value from malloc

Quote:

<snip>

> However, I can see several equally valid reasons for using the cast.
> For one thing, *not* using the cast can *also* mask problems the
> compiler would otherwise warn you about, such as malloc'ing space for
> the wrong type.  If I write

>   int* foo;
>   foo = malloc(100 * sizeof(int));

> and later change foo's type to long* without remembering to fix
> malloc's argument, the compiler will not catch the error.

Write it as foo = malloc(100 * sizeof *foo) instead.

Quote:
> But the
> compiler is required to issue a diagnostic for

>   long* foo;
>   foo = (int*) malloc(100 * sizeof(int));

True enough, but not for

long *foo;
foo = malloc(100 * sizeof *foo);

Quote:
> Secondly, including the cast serves as a reminder to the programmer
> of the type of object for which space is being allocated.  In this
> respect it has the same role as good commenting or good variable
> naming conventions.

If the type of the object is not available for scrutiny within a couple
of PgUps, the function is probably too long. In any case, at least one
very popular IDE editor now lets you jump to an object's declaration
with a single keystroke, and back again with another single keystroke. I
suspect it is not alone in this regard.

Quote:
> Lastly, including the cast will make it easier to port the code to
> C++ should this ever become necessary or desired.  It is not always
> possible to program entirely in the common subset of C and C++, but
> in this case little is lost by doing so.

When/if you port the code to C++, you want to change all those mallocs
to news anyway, so the point is moot. :-)

<snip>

--

"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton



Mon, 07 Mar 2005 07:18:47 GMT  
 casting return value from malloc

[casting malloc]

Quote:
> However, I can see several equally valid reasons for using the cast.
> For one thing, *not* using the cast can *also* mask problems the
> compiler would otherwise warn you about, such as malloc'ing space for
> the wrong type.  If I write

>   int* foo;
>   foo = malloc(100 * sizeof(int));

This would not be a problem if you wrote the sizeof usage
correctly.  When calling malloc(), I recommend using the sizeof
operator on the object you are allocating, not on the type.  For
instance, *don't* write this:

        int *x = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

        int *x = malloc (sizeof *x * 128);

There's a few reasons to do it this way:

        * If you ever change the type that `x' points to, it's not
          necessary to change the malloc() call as well.

          This is more of a problem in a large program, but it's still
          convenient in a small one.

        * Taking the size of an object makes writing the statement
          less error-prone.  You can verify that the sizeof syntax is
          correct without having to look at the declaration.

Quote:
> Secondly, including the cast serves as a reminder to the programmer
> of the type of object for which space is being allocated.  In this
> respect it has the same role as good commenting or good variable
> naming conventions.

The variable name should normally be enough of a hint of its
type.

Quote:
> Lastly, including the cast will make it easier to port the code to
> C++ should this ever become necessary or desired.  It is not always
> possible to program entirely in the common subset of C and C++, but
> in this case little is lost by doing so.

You should know what language you're writing in advance.  If
you're using malloc() in C++ then you're probably doing something
wrong.
--
"The way I see it, an intelligent person who disagrees with me is
 probably the most important person I'll interact with on any given
 day."
--Billy Chambless


Mon, 07 Mar 2005 07:44:41 GMT  
 casting return value from malloc

Quote:

>(Sorry if this message appears more than once... my news server is
>acting weird.)

>People here typically say that we should not cast the return value
>from malloc() and related functions because it is unnecessary and can
>mask problems the compiler would otherwise warn you about, such as
>not including stdlib.h.

Yes.  This is a tired old issue.  Please search the archives for tons
of discussion on this.

Quote:
>However, I can see several equally valid reasons for using the cast.
>For one thing, *not* using the cast can *also* mask problems the
>compiler would otherwise warn you about, such as malloc'ing space for
>the wrong type.  If I write

>  int* foo;
>  foo = malloc(100 * sizeof(int));

>and later change foo's type to long* without remembering to fix
>malloc's argument, the compiler will not catch the error.  But the
>compiler is required to issue a diagnostic for

>  long* foo;
>  foo = (int*) malloc(100 * sizeof(int));

Try

  foo = malloc(100 * sizeof(*foo));

Quote:
>Secondly, including the cast serves as a reminder to the programmer
>of the type of object for which space is being allocated.  In this
>respect it has the same role as good commenting or good variable
>naming conventions.

Eeek, I suppose you subscribe to the "Hungarian" school of thought?

The nice thing about writing malloc()s the "clc Way", is that you don't
have to know or care the type of the object.  To find out the type, you
look at the definition of the object, up above, just as you do if you
want to know the types involved in, say, a plain assignment.  You wouldn't
recommend writing

    int i, j;

    /*  ...  */

    i = (int)j;

would you?  But doesn't the cast "document" the type here, too?
What's the difference?

Quote:
>Lastly, including the cast will make it easier to port the code to
>C++ should this ever become necessary or desired.  It is not always
>possible to program entirely in the common subset of C and C++, but
>in this case little is lost by doing so.

IMO, much is lost.  If you need to be portable to C++, consider using
macros or similar techniques, to include the cast only when it is
needed.  The same kinds of tricks are needed to robustly program in
an environment where your code might encounter K&R (pre-ANSI, no
function prototypes) compilers; rather than just doing away with
prototypes to satisfy the lowest common denominator, it is preferable
to use macros or other tricks to include the prototypes when they
will be understood.  You can see this in a lot of GNU source code.

Quote:
>These, combined with the fact that AFAIK most compilers will complain
>about calling malloc without stdlib.h regardless of whether a cast is
>present, make me wonder if the wisdom of not casting should be
>reevaluated.  Perhaps at the very least it should be considered an
>issue of personal coding style, similar in status to indentation size
>or curly brace placement, rather than something for which posters to
>comp.lang.c are regularly admonished.

Posters to comp.lang.c are regularly admonished for poor indentation
and/or curly brace placement, as is proper!  Four spaces, never a TAB,
K&R brace style.  Don't cast malloc(), don't void main(), don't use
gets().  :)

(In seriousness, posters are usually only admonished for horrible,
human-antagonistic indentation and brace placement, such as "everything
starts in column 1" or "no discernable layout to it at all, looks like OCR
of the top two inches of the shredder bin".  The different *sane* coding
styles are all acceptable here.)

Quote:
>What do the experts think?

Couldn't tell ya, but there you have what *I* think.

--Ben

--



Mon, 07 Mar 2005 07:45:09 GMT  
 casting return value from malloc

Quote:

>People here typically say that we should not cast the return value
>from malloc() and related functions because it is unnecessary and can
>mask problems the compiler would otherwise warn you about, such as
>not including stdlib.h.

>However, I can see several equally valid reasons for using the cast.
>For one thing, *not* using the cast can *also* mask problems the
>compiler would otherwise warn you about, such as [a problem that

 occurs if you change the type of a variable without changing its
 name].

In addition to what others have mentioned (which boils down to "use
sizeof *ptr" rather than sizeof(type)), I will point out that the
former error -- failing to include the appropriate header -- happens
all the time (I have even done it myself), while the latter error
is rare in my experience: so much so that not only have I never
*done* it, I have never even *seen* it.

Quote:
>Secondly, including the cast serves as a reminder to the programmer
>of the type of object for which space is being allocated. ...

As others noted, this is the same argument that leads to vWriting
adjPointless nPrefixes prepIn prepFront prepOf nVariable nNames. :-)

Quote:
>Lastly, including the cast will make it easier to port the code to
>C++ should this ever become necessary or desired.

If you want to use C code in a C++ project, compile the C code with
a C compiler, and use C++'s `extern "C"' feature to access it.
This will avoid not only obvious problems (that draw diagnostics)
like uncast malloc() calls, but less-obvious ones like sizeof('x')
changing to 1.  There are a number of (admittedly mostly unlikely)
code sequences that are legal in *both* languages, but have different,
sometimes profoundly different, semantics in each.

Quote:
>These, combined with the fact that AFAIK most compilers will complain
>about calling malloc without stdlib.h regardless of whether a cast is
>present ...

I think this still falls into the "some" category, not the "most"
one, and probably will for a few more years.

When it does, I think that the issue will be much more "style", in
the same way that (pseudo)Hungarian Notation is an issue of "style",
as in: "There is no single `good' style, but there are plenty of
bad ones." :-)
--
In-Real-Life: Chris Torek, Wind River Systems (BSD engineering)

http://67.40.109.61/torek/  (for the moment)
(you probably cannot email me -- spam has effectively killed email)



Mon, 07 Mar 2005 08:49:03 GMT  
 casting return value from malloc
I disagree. Please see my comments below.



Quote:
>(Sorry if this message appears more than once... my news server is
>acting weird.)

>People here typically say that we should not cast the return value
>from malloc() and related functions because it is unnecessary and can
>mask problems the compiler would otherwise warn you about, such as
>not including stdlib.h.

>However, I can see several equally valid reasons for using the cast.
>For one thing, *not* using the cast can *also* mask problems the
>compiler would otherwise warn you about, such as malloc'ing space for
>the wrong type.  If I write

>  int* foo;
>  foo = malloc(100 * sizeof(int));

>and later change foo's type to long* without remembering to fix
>malloc's argument, the compiler will not catch the error.

Precisely why I would never hard-code the type of the variable into
the malloc call. Try this:

anytype *foo;
foo = malloc(100 * sizeof *foo);

Now there's no need to check/repair every single malloc when you
change the type of a pointer.

<snip>

Quote:

>Secondly, including the cast serves as a reminder to the programmer
>of the type of object for which space is being allocated.  In this
>respect it has the same role as good commenting or good variable
>naming conventions.

What, like that hungarian notation crap? I'm not sure why anybody
thinks it is a good idea to bind the variable's name to its type. As
you mentioned before, types sometimes need to change. Do you want to
track down every instance of the variable name and update that also? I
don't. Besides that, it makes horribly ugly variable names that don't
do much for readability.

Seriously, I don't see this as much of an advantage. So I know the
type. Great. If I'd forgotten it, I would have looked at the
declaration. But again, I have to track down and fix several mallocs
if the type changes.

Quote:

>Lastly, including the cast will make it easier to port the code to
>C++ should this ever become necessary or desired.  It is not always
>possible to program entirely in the common subset of C and C++, but
>in this case little is lost by doing so.

I was just saying in another thread that porting from C to C++ seems
basically useless. Just compile your C source as C, use an extern "C"
block around the #incldue statement in your C++ source, and link them
together. Much less messy, IMHO.

Quote:

>These, combined with the fact that AFAIK most compilers will complain
>about calling malloc without stdlib.h regardless of whether a cast is
>present, make me wonder if the wisdom of not casting should be
>reevaluated.

A compiler isn't required to warn about it. It is (I think) required
to implicitly declare it at the first use if it's not already
declared. Basically this is a bad bet - if you cast, you could lose
big time; if you don't cast, you're guaranteed to win.

Quote:
>Perhaps at the very least it should be considered an
>issue of personal coding style, similar in status to indentation size
>or curly brace placement, rather than something for which posters to
>comp.lang.c are regularly admonished.

I don't think the folks here have ever claimed it's anything other
than good style to leave out the cast.

Quote:

>What do the experts think?

We'll have to wait and see...

-Kevin



Mon, 07 Mar 2005 09:40:03 GMT  
 casting return value from malloc

Quote:

> However, I can see several equally valid reasons for using the cast.
> For one thing, *not* using the cast can *also* mask problems the
> compiler would otherwise warn you about, such as malloc'ing space for
> the wrong type.  If I write

>   int* foo;
>   foo = malloc(100 * sizeof(int));

> and later change foo's type to long* without remembering to fix
> malloc's argument, the compiler will not catch the error.

You could right it correctly in the first place:
   foo = malloc(NUMBER_OF_FOOS * sizeof *foo);


Mon, 07 Mar 2005 16:16:35 GMT  
 casting return value from malloc

Quote:

>(Sorry if this message appears more than once... my news server is
>acting weird.)

>People here typically say that we should not cast the return value
>from malloc() and related functions because it is unnecessary and can
>mask problems the compiler would otherwise warn you about, such as
>not including stdlib.h.

>However, I can see several equally valid reasons for using the cast.
>For one thing, *not* using the cast can *also* mask problems the
>compiler would otherwise warn you about, such as malloc'ing space for
>the wrong type.  If I write

>  int* foo;
>  foo = malloc(100 * sizeof(int));

>and later change foo's type to long* without remembering to fix
>malloc's argument, the compiler will not catch the error.  But the
>compiler is required to issue a diagnostic for

>  long* foo;
>  foo = (int*) malloc(100 * sizeof(int));

You'll loose anyway, because you gets NO warning from compiler if
you've vorgot to include the standard header and produces unwanded
crashes, as the compiler ssuems malloc returns int - not void* as it
really does.

In any case casting the return of malloc is undefined behavior.

Get a mshine that has
sizeof(void*) == 8      or even 4
sizeof(int)   == 4              2

you'll loose some signifcant bits of the address returned by malloc if
you casts the result of the undefined malloc().

Casting the result of malloc is aways more dangerous than trying to
repair errors in the size parameter,

--
Tschau/Bye
        Herbert

http://www.pc-rosenau.de
the point to buy eComStation in germany



Mon, 07 Mar 2005 18:47:10 GMT  
 casting return value from malloc

...

Quote:
> In any case casting the return of malloc is undefined behavior.

Not at all. casting itself does not cause undefined behavior. You
probably meant that it would cause UB in the case where a
prototype was absent (well actually a declaration), and even than
this is probably not the case.

--

"LISP  is worth learning for  the profound enlightenment  experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days."   -- Eric S. Raymond



Mon, 07 Mar 2005 19:20:18 GMT  
 casting return value from malloc

<SNIP>

: These, combined with the fact that AFAIK most compilers will complain
: about calling malloc without stdlib.h regardless of whether a cast is
: present, make me wonder if the wisdom of not casting should be
: reevaluated.  Perhaps at the very least it should be considered an
: issue of personal coding style, similar in status to indentation size
: or curly brace placement, rather than something for which posters to
: comp.lang.c are regularly admonished.
:
: What do the experts think?
: --Steve

I can tell you that in my 12 (or 13 or 14...) some years of
"professional" programming, and doing a LOT of maintenance,
casting the return of malloc() has never actually helped, and
it has hurt many, many times (especially now that we're moving
to 64-bit CPUs where sizeof(int) != sizeof(void *)).

Actual experience has taught me to avoid casting malloc().

-Ed



Tue, 08 Mar 2005 01:12:12 GMT  
 casting return value from malloc
On Thu, 19 Sep 2002 11:20:18 UTC, "Zoran Cutura"

Quote:


>....
>> In any case casting the return of malloc is undefined behavior.

>Not at all. casting itself does not cause undefined behavior. You
>probably meant that it would cause UB in the case where a
>prototype was absent (well actually a declaration), and even than
>this is probably not the case.

Yes, but in any case it IS undefined behavior. Even when yet occures
anything you wants, at next compiletime it may change its behavior.

If you have the right prototype right there then casting is truly
superflous and may be wrong if you changes the type of the destination
variable. So casting the return value of malloc() is always dangerous.

--
Tschau/Bye
        Herbert

http://www.pc-rosenau.de
the point to buy eComStation in germany



Tue, 08 Mar 2005 04:19:21 GMT  
 casting return value from malloc
Many people in this thread have said that casting the return value
from malloc is not only bad style: it is undefined! If that is the
case, why does K&R2 cast the return value of malloc in numerous
places?


Tue, 08 Mar 2005 10:08:54 GMT  
 casting return value from malloc
Submitted by "F. H." to comp.lang.c:

Quote:
> Many people in this thread have said that casting the return value
> from malloc is not only bad style: it is undefined! If that is the
> case, why does K&R2 cast the return value of malloc in numerous
> places?

Because in K&R C the return type of malloc() was char*, not
void*.  Also, K&R C is not ISO C.

--
Andreas K?h?ri                  +-----{ Have a Unix: netbsd.org
Otago, New Zealand              | :-)
--------------------------------+-----{ This post ends with :wq



Tue, 08 Mar 2005 10:12:29 GMT  
 casting return value from malloc

Quote:

> Many people in this thread have said that casting the return value
> from malloc is not only bad style: it is undefined!

It is only undefined if you failed to #include <stdlib.h>.

Quote:
> If that is the case, why does K&R2 cast the return value of
> malloc in numerous places?

It's an erratum.


Tue, 08 Mar 2005 10:12:40 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. (void *) & casting the pointer returned by malloc

2. Why cast malloc's return?

3. Casting return value to Typedef enum?

4. Casting the return value from SelectObject

5. return value of malloc()

6. malloc: to cast or not to cast

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

8. malloc crashes - malloc(256) returns 0(!) (_MT)

9. Returning error values vs. not returning

10. Simple C++ question: Using return values (by value)

11. casting malloc question.

12. casting malloc question.

 

 
Powered by phpBB® Forum Software