Why not cast the rerurn from malloc()? 
Author Message
 Why not cast the rerurn from malloc()?

Quote:

> Many thanks for all your explanations on the casting malloc() question.
> I understand now.

Part of what you had earlier indicated was ``confusion'' about the
casting of malloc may have stemmed from K&R2 (the ANSI C, Second Edition).
In the ``Storage Management'' description [7.8.5], it states:

``The pointer returned by _malloc_ or _calloc_ has the proper alignment
for the object in question, but it must be cast into the appropriate
type...''

Naturally, since the K&R2 book does not define the C programming language,
this admonition (``must be cast'') has no standing.

--
========================================================================

       Well...Unix, of course. Because windoze is a pathethic toy...
      Yes, Texas, of course. Because anywhere else is just a place...



Tue, 11 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?

|> Every current C compiler in my possession complains when a prototype is
|> missing.  Now, I don't know for sure if this is _required_ by the language
|> specification, but for all practical purposes it happens.  So when I type:
|>
|> #include <stdio.h>
|> char *foo(size_t nbytes)
|> {
|>    return (char *) malloc(nbytes); /* IT'S JUST AN EXAMPLE -- OK! */
|> }
|> And some loony changes my code in the project to:
|>
|> /* I often forget to end comments...
|> #include <stdio.h>
|> /* This function is pretty dull... */
|> char *foo(size_t nbytes)
|> {
|>    return (char *) malloc(nbytes); /* IT'S JUST AN EXAMPLE -- OK! */
|> }

Well, since malloc() isn't prototyped in <stdio.h>, you should get
the warnings for *both* examples. :-)

That aside, warnings about calls to undeclared functions are nice, but
only if they are left as an option.  There is far too much legacy code
written before the advent of function prototypes to consider a compiler
which issues such warnings *by default* as programmer-friendly.

Regards,

--
Chris Engebretson - Raytheon STX Corporation | Ph#: (605)594-6829
USGS EROS Data Center, Sioux Falls, SD 57198 | Fax: (605)594-6940

Opinions are not those of  Raytheon Systems Company  or the USGS.



Tue, 11 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?

Quote:


> > Many thanks for all your explanations on the casting malloc()
> > question. I understand now.

> Part of what you had earlier indicated was ``confusion'' about the
> casting of malloc may have stemmed from K&R2 (the ANSI C, Second
> Edition).
> In the ``Storage Management'' description [7.8.5], it states:

K&R C had no void pointer type, so malloc was defined like this:

char *malloc();

A typecast *was* necessary when you were allocating things
other than chars to avoid "type mismatch" warnings.

In ANSI C this is no longer an issue so the typecast should
be avoided.

--
<\___/>
/ O O \
\_____/ FTB.



Tue, 11 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?

Quote:


> > Part of what you had earlier indicated was ``confusion'' about the
> > casting of malloc may have stemmed from K&R2 (the ANSI C, Second
> > Edition).
> > In the ``Storage Management'' description [7.8.5], it states:
> K&R C had no void pointer type, so malloc was defined like this:
> char *malloc();
> A typecast *was* necessary when you were allocating things
> other than chars to avoid "type mismatch" warnings.

This is perhaps of interest from an historical perspective. However,
note that my article was about ``K&R2'', ``ANSI C'' and ``Second
Edition''. The passage referenced [7.8.5] shows both malloc and
calloc prototyped with the ``void *'' return.

--
========================================================================

       Well...Unix, of course. Because windoze is a pathethic toy...
      Yes, Texas, of course. Because anywhere else is just a place...



Tue, 11 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?

Ulric Eriksson wrote in a message to All:

Quote:
>If you cast the result of malloc then *some* compilers will still
> detect
>the error of not including stdlib.h.  If you don't cast the result
>of malloc then *all* compilers will detect it.

 UE> And the list of compilers which won't detect it is...?

At least Borland (v3.0) and Watcom (v10.6) silently compile this (at
default warning levels, that is) :

int main(void)
{
   char *p = (char *)malloc(100);
   free(p);
   return 0;

Quote:
}

greetings,
Tom



Wed, 12 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:

>At least Borland (v3.0) and Watcom (v10.6) silently compile this (at
>default warning levels, that is) :

Only use defaults if you don't care what they are. GCC by default
doesn't compile C. Most compilers by default do not optimize.

It is necessary for a compiler to have a "shut up and compile" mode
in order to compile prehistoric code without intolerable noise.

Ulric
--
Another opinion presented as fact.



Thu, 13 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:



>>If you get a warning about there being no prototype for malloc() in
>>scope then your code is broken, pure and simple.  No amount of casting
>>will cure it.

>>This is the reason for advising against casting the result of malloc().
>>If you cast the result of malloc then *some* compilers will still detect
>>the error of not including stdlib.h.  If you don't cast the result
>>of malloc then *all* compilers will detect it.

>And the list of compilers which won't detect it is...?

...depressingly long.  Even "gcc -ansi -pedantic" silently swallows it.

Quote:

>This issue belongs in the same category as

>    if ('\0' = *p)

>i.e. a hack to detect one instance of an error is promoted to religion,
>without actually solving anything.

Nonsense.  It solves a very real problem, and actually involves *less*
work than doing it the inferior way.  You only have to look back a few
weeks in this group to find several postings by people bitten by the
"failure to include stdlib.h" error and who had failed to spot the
problem *precisely because* they had cast the result of malloc.  (And this
is since the last time you claimed it didn't solve a real problem.)

Yes, if there were a drawback to missing out the cast you could weigh
this benefit against the drawback, but there isn't one.

This is in any case just a particular case of the stylistic rule "minimise
casting", or "never cast if you don't need to".  If there are lots of
casts in your code you're doing something wrong.

Quote:
>The proper solution to finding missing prototypes is to let the
>compiler produce diagnostics for missing prototypes.

That is indeed a good solution if:

a) Your compiler supports that facility or you have a lint-like tool available
   to you.
b) The code with which you're dealing doesn't contain thousands of instances
   of unprototyped calls spread over hundreds of source files.

Code of the second type is depressingly common.  You may not write it and
I certainly don't, but it does exist in very large quantities.  Your method
is then totally useless, but the recommended technique of not casting
the result of malloc *continues to work* and works well.  What's more it
doesn't cost you anything and actually involves less typing.

So, the advantage of following this stylistic recommendation is that gives
you improved error detection and the disadvantage is...  it doesn't have
one (except it doesn't happen to be the way some people do it and they
can't bear to admit that their coding style could be improved).

John
--
John Winters.  Wallingford, Oxon, England.

The Linux Emporium - a source for Linux CDs in the UK
See <http://www.polo.demon.co.uk/emporium.html>



Thu, 13 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:



>>And the list of compilers which won't detect it is...?

>...depressingly long.  Even "gcc -ansi -pedantic" silently swallows it.

Yes, it "even swallows it" in minimum warning mode.

If you have a list, please feel free to post it. I would be interested
to see it. But please only include real entries, not ones you have made
up by carefully selecting the right set of options. Take your time.

Quote:
>Nonsense.  It solves a very real problem, and actually involves *less*
>work than doing it the inferior way.  You only have to look back a few
>weeks in this group to find several postings by people bitten by the
>"failure to include stdlib.h" error and who had failed to spot the
>problem *precisely because* they had cast the result of malloc.  (And this
>is since the last time you claimed it didn't solve a real problem.)

There have been no such postings. If you had read the postings properly
you would perhaps have understood the nature of the code and that they
had in fact spotted the error *despite* the cast.

Quote:
>Code of the second type is depressingly common.  You may not write it and
>I certainly don't, but it does exist in very large quantities.  Your method
>is then totally useless, but the recommended technique of not casting
>the result of malloc *continues to work* and works well.  What's more it
>doesn't cost you anything and actually involves less typing.

You actually believe deleting thousands of casts is easier than adding
the prototypes? And you also believe that the code will be correct just
by deleting the casts? What language are you talking about?

I really don't have the patience to argue with you over your religious
beliefs. The casts are a matter of stylistic preferences.

Ulric
--
Another opinion presented as fact.



Fri, 14 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:





>>>And the list of compilers which won't detect it is...?

>>...depressingly long.  Even "gcc -ansi -pedantic" silently swallows it.

>Yes, it "even swallows it" in minimum warning mode.

This is far from "minimum warning" mode.

Quote:
>>Nonsense.  It solves a very real problem, and actually involves *less*
>>work than doing it the inferior way.  You only have to look back a few
>>weeks in this group to find several postings by people bitten by the
>>"failure to include stdlib.h" error and who had failed to spot the
>>problem *precisely because* they had cast the result of malloc.  (And this
>>is since the last time you claimed it didn't solve a real problem.)

>There have been no such postings.

Now why would you say such a silly thing?  Anyone with access to DejaNews

Quote:
>If you had read the postings properly
>you would perhaps have understood the nature of the code and that they
>had in fact spotted the error *despite* the cast.

Ah, the Longstreet argument.  "If you disagree with me it's because
you don't understand."  Well if you care to go back and *read what I
wrote* it will be clear that I did fully understand the nature of the code.
It will also be clear the poster had not spotted the error (or indeed
he wouldn't have posted asking for an explanation) and had the cast been
missed out the other compiler would also have pointed out the error.
Both your assertions in the above paragraph are thus false.

Quote:
>>Code of the second type is depressingly common.  You may not write it and
>>I certainly don't, but it does exist in very large quantities.  Your method
>>is then totally useless, but the recommended technique of not casting
>>the result of malloc *continues to work* and works well.  What's more it
>>doesn't cost you anything and actually involves less typing.

>You actually believe deleting thousands of casts is easier than adding
>the prototypes?

Where did I suggest going through deleting casts (or for that matter,
not adding prototypes)?  This is a pathetic form of argument - pretend
your opponent said something silly which he didn't say, then point out
it's silly.  You lose again.

Quote:
>And you also believe that the code will be correct just
>by deleting the casts?

No.  Second attempt at using deceptive argument technique.  Failed again.

Quote:
>What language are you talking about?

C.  This newsgroup is for the discussion of the C programming language.

Quote:
>I really don't have the patience to argue with you over your religious
>beliefs.

Ah, not only the Longstreet technique but also the Nudds approach - "If
you disagree with me then it's due to your religious beliefs".  Sorry,
that one doesn't wash either.

Quote:
>The casts are a matter of stylistic preferences.

Indeed.  No-one has suggested otherwise, but missing them out is a win-win
option so it's a good stylistic approach to adopt.

And as far as I'm concerned, that's the end of the thread for me.  Unless
you can come up with any real disadvantages of the approach which don't
involve mythical languages I won't respond to any more of your attempts
to obfuscate the issue.

John

--
John Winters.  Wallingford, Oxon, England.

The Linux Emporium - a source for Linux CDs in the UK
See <http://www.polo.demon.co.uk/emporium.html>



Fri, 14 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?

I lint everything.  Here is the lint output for that file:
C:\TMP>type _lint.tmp   | more

--- Module:   oops.c
                     _
   char *p = (char *)malloc(100);
oops.c(3) : Error 1055: malloc undeclared, assumed to return int
oops.c(3) : Info 746: call to malloc() not made in the presence of a prototype
   _
   free(p);
oops.c(4) : Error 1055: free undeclared, assumed to return int
oops.c(4) : Info 746: call to free() not made in the presence of a prototype

--- Global Wrap-up

Warning 526: free() (line 4, file oops.c) not defined
Warning 628: no argument information provided for function free() (line 4,
file
    oops.c)
Warning 526: malloc() (line 3, file oops.c) not defined
Warning 628: no argument information provided for function malloc() (line 3,
    file oops.c)

---
PC-lint for C/C++ output placed in _LINT.TMP

--
Hypertext C-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-FAQ ftp: ftp://rtfm.mit.edu, C-FAQ Book: ISBN 0-201-84519-9
Try "C Programming: A Modern Approach" ISBN 0-393-96945-2
Want Software?  Algorithms?  Pubs? http://www.infoseek.com

Quote:

>Ulric Eriksson wrote in a message to All:

>>If you cast the result of malloc then *some* compilers will still
>> detect
>>the error of not including stdlib.h.  If you don't cast the result
>>of malloc then *all* compilers will detect it.

> UE> And the list of compilers which won't detect it is...?

>At least Borland (v3.0) and Watcom (v10.6) silently compile this (at
>default warning levels, that is) :

>int main(void)
>{
>   char *p = (char *)malloc(100);
>   free(p);
>   return 0;
>}

>greetings,
>Tom




Fri, 14 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:

>Now why would you say such a silly thing?

>Ah, the Longstreet argument. "If you disagree with me it's because
>you don't understand."

>This is a pathetic form of argument

>Second attempt at using deceptive argument technique.

>Ah, not only the Longstreet technique but also the Nudds approach

>I won't respond to any more of your attempts
>to obfuscate the issue.

Uh-huh. Guess you must be right, then.

Ulric
--
Another opinion presented as fact.



Fri, 14 Jul 2000 03:00:00 GMT  
 Why not cast the rerurn from malloc()?


Quote:

> > Even "gcc -ansi -pedantic" silently swallows it.

> Yes, it "even swallows it" in minimum warning mode.

Incorrect. '-ansi -pedantic' activates every diagnostic required by the
standard, and turns off every diagnostic -not- required. Adding, say,
'-Wall' (which would detect the error, btw) makes 'gcc' non-conformant.

--
The FAQ, like the C standard (and, for that matter, the Bible and the US
Constitution) is often used as an authority by clueless people who don't
seem to have read it, at least not with any level of comprehension.



Fri, 14 Jul 2000 03:00:00 GMT  
 
 [ 31 post ]  Go to page: [1] [2] [3]

 Relevant Pages 
 

 
Powered by phpBB® Forum Software