Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Casting return of malloc

Reply
Thread Tools

Casting return of malloc

 
 
ytrama@gmail.com
Guest
Posts: n/a
 
      02-08-2005
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

 
Reply With Quote
 
 
 
 
Dave Vandervies
Guest
Posts: n/a
 
      02-08-2005
In article <(E-Mail Removed) .com>,
http://www.velocityreviews.com/forums/(E-Mail Removed) <(E-Mail Removed)> 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 (E-Mail Removed)
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
 
Reply With Quote
 
 
 
 
Joona I Palaste
Guest
Posts: n/a
 
      02-08-2005
(E-Mail Removed) <(E-Mail Removed)> 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 ((E-Mail Removed)) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"We sorcerers don't like to eat our words, so to say."
- Sparrowhawk
 
Reply With Quote
 
E. Robert Tisdale
Guest
Posts: n/a
 
      02-08-2005
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(12;
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(12;
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*'
 
Reply With Quote
 
Ben Pfaff
Guest
Posts: n/a
 
      02-08-2005
"(E-Mail Removed)" <(E-Mail Removed)> 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$(E-Mail Removed)>).

--
"This is a wonderful answer.
It's off-topic, it's incorrect, and it doesn't answer the question."
--Richard Heathfield
 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      02-08-2005
Ben Pfaff wrote:
> "(E-Mail Removed)" <(E-Mail Removed)> 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$(E-Mail Removed)>).


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

 
Reply With Quote
 
Flash Gordon
Guest
Posts: n/a
 
      02-08-2005
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(12;
> 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.
 
Reply With Quote
 
E. Robert Tisdale
Guest
Posts: n/a
 
      02-08-2005
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$(E-Mail Removed)>).


Did you really mean to post an email address here?

 
Reply With Quote
 
Mike Wahler
Guest
Posts: n/a
 
      02-08-2005
<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) oups.com...
> 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


 
Reply With Quote
 
Keith Thompson
Guest
Posts: n/a
 
      02-08-2005
Ben Pfaff <(E-Mail Removed)> writes:
> "(E-Mail Removed)" <(E-Mail Removed)> 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$(E-Mail Removed)>).


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) (E-Mail Removed) <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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How to check whether malloc has allocated memory properly in caseif malloc(0) can return valid pointer Gene C Programming 0 12-20-2010 05:33 AM
Casting the return value of malloc() ? Tinkertim C Programming 82 10-20-2008 12:45 AM
Malloc/Free - freeing memory allocated by malloc Peter C Programming 34 10-22-2004 10:23 AM
free'ing malloc'd structure with malloc'd members John C Programming 13 08-02-2004 11:45 AM
Re: free'ing malloc'd structure with malloc'd members ravi C Programming 0 07-30-2004 12:42 PM



Advertisments