Yugi said:
Is it ok to cast the return value of malloc ?
Because somewhere in this group i read the following...
Do not cast return value of malloc().It's not required, and it masks
failure to include <stdlib.h>.
Could someone explain me this behaviour??
Casting the result of malloc() is permissible in the
sense that it will not break the program (if you do it
correctly). It is also permissible in the sense that you
will not actually be burned at the stake for doing it.
However, it is unnecessary in C programs: malloc()
returns a `void*' value, and this kind of pointer can be
converted to any other kind of data pointer without a cast.
`(char*)malloc(42)' is thus a little bit like `(int)42'
or `(double)3.14159' -- extra clutter that adds nothing
to the program.
The cast can also prevent the compiler from warning
you that you have failed to declare malloc() correctly,
which you ordinarily do by including <stdlib.h>. If you
call a function that has not been declared, the compiler
assumes that the function returns an `int'. This can lead
to trouble because malloc() does not return an `int', and
when the caller tries to retrieve the returned value it may
get the wrong result (e.g., on a machine with 32-bit `int'
and 64-bit `void*'). If you write `char *p = malloc(42);'
the compiler will see that you are trying to assign an `int'
value to a pointer and will issue a diagnostic; this will
(one hopes) remind you to add #include <stdlib.h> to fix the
error.
However, if you write `char *p = (char*)malloc(42);' the
compiler sees that you are *converting* an `int' to a pointer
(an operation that is dubious but permitted) and may not give
any warnings at all. The error will not be detected until
the program misbehaves -- and that might not be until you
port the code to another machine or something. Errors cost
more the longer they sit undetected in the code, so silencing
the warning increases your development and support costs.
Some compilers will warn about the use of an undeclared
function, cast or no cast, if their warning sensitivity is
turned up high enough. It is an excellent idea to operate
your compiler in such a mode, if it has one. Also, the latest
"C99" Standard *requires* a diagnostic for the use of undeclared
functions, so the problem may fade away as C99 compilers become
more widespread (which is taking a l-o-n-g time; don't hold
your breath).
Finally, casting the result of malloc() is *mandatory* in
a C++ program, because the rules of C++ are different from
those of C. In "pure C++" code you probably shouldn't use
malloc() very much anyhow; C++ has other ways to manage memory.
But if you are writing code that (for some strange reason) must
have a "dual personality" and work both as C and C++, you will
need to cast the result of malloc() -- and suffer the scorn of
both the C and C++ communities.