Re: Casting the return value of malloc() ?
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Thu, 02 Oct 2008 12:12:01 +0000
polas said:
<snip>
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted.
If you mean "unnecessary", you're right.
Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly) from malloc
In C90, whenever the compiler encounters any call to any function for which
it has not yet seen a declaration, it is required to assume that the
function returns int, even if We Know Different. (And indeed even if the
compiler knows different, which it is allowed to but not required to.)
Since you're assigning the value returned by malloc to a pointer object,
omitting the header therefore gives a type mismatch between int and
pointer, which the compiler is obliged to diagnose - UNLESS you foolishly
cast the diagnosis away.
If pointers are returned in a different way to ints, or if pointers are
longer than ints, or have completely different representations, this can
cause a very real problem.
and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour
Yes, that's almost right - casting the value will hide the problem and
*may* result in strange behaviour. Or it may not. Until your boss is
watching...
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.
- Follow-Ups:
- Re: Casting the return value of malloc() ?
- From: polas
- Re: Casting the return value of malloc() ?
- References:
- Casting the return value of malloc() ?
- From: Tinkertim
- Re: Casting the return value of malloc() ?
- From: Nick Keighley
- Re: Casting the return value of malloc() ?
- From: polas
- Casting the return value of malloc() ?
- Prev by Date: Re: code
- Next by Date: Re: Casting the return value of malloc() ?
- Previous by thread: Re: Casting the return value of malloc() ?
- Next by thread: Re: Casting the return value of malloc() ?
- Index(es):
Relevant Pages
|