Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Casting return of malloc (http://www.velocityreviews.com/forums/t436836-casting-return-of-malloc.html)

ytrama@gmail.com 02-08-2005 04:12 PM

Casting return of malloc
 
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


Dave Vandervies 02-08-2005 04:19 PM

Re: Casting return of malloc
 
In article <1107879170.767254.109430@g14g2000cwa.googlegroups .com>,
ytrama@gmail.com <ytrama@gmail.com> 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 dj3vande@csclub.uwaterloo.ca
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

Joona I Palaste 02-08-2005 04:20 PM

Re: Casting return of malloc
 
ytrama@gmail.com <ytrama@gmail.com> 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 (palaste@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"We sorcerers don't like to eat our words, so to say."
- Sparrowhawk

E. Robert Tisdale 02-08-2005 05:06 PM

Re: Casting return of malloc
 
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*'

Ben Pfaff 02-08-2005 05:36 PM

Re: Casting return of malloc
 
"ytrama@gmail.com" <ytrama@gmail.com> 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$nK2.4505@nwrddc01.gnilink.net>).

--
"This is a wonderful answer.
It's off-topic, it's incorrect, and it doesn't answer the question."
--Richard Heathfield

CBFalconer 02-08-2005 06:48 PM

Re: Casting return of malloc
 
Ben Pfaff wrote:
> "ytrama@gmail.com" <ytrama@gmail.com> 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$nK2.4505@nwrddc01.gnilink.net>).


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


Flash Gordon 02-08-2005 07:00 PM

Re: Casting return of malloc
 
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.

E. Robert Tisdale 02-08-2005 07:01 PM

Re: Casting return of malloc
 
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$nK2.4505@nwrddc01.gnilink.net>).


Did you really mean to post an email address here?


Mike Wahler 02-08-2005 07:02 PM

Re: Casting return of malloc
 
<ytrama@gmail.com> wrote in message
news:1107879170.767254.109430@g14g2000cwa.googlegr 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



Keith Thompson 02-08-2005 07:11 PM

Re: Casting return of malloc
 
Ben Pfaff <blp@cs.stanford.edu> writes:
> "ytrama@gmail.com" <ytrama@gmail.com> 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$nK2.4505@nwrddc01.gnilink.net>).


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) kst-u@mib.org <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.


All times are GMT. The time now is 10:45 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.