It is very common to see in C code a typecast applied to the value returned from malloc():
#include <stdlib.h>
/* ... */
{
int *p = (int*) malloc(100*sizeof(int));
/* ... */
}
This style was advised (by
K&R!) in the days of "classic" C, but is highly inadvisable when using an
ANSI C compiler (the only compiler you'll find today). Still, you'll find it in
the ten commandments for C programmers --
old habits die hard.
Here's why: Nowadays, the return value of malloc has type void *
, which may safely be converted to any other pointer type (note that this is not true of other void pointers; generally, a void pointer may only be converted back to a type of pointer compatible with the pointer value used to create it). So you may safely leave out the (int *)
cast above. But what harm can leaving it in do?
Turns out it can do a lot of harm. Say you forgot to "#include <stdlib.h>
". Then malloc() has implicit return type int
. And the cast to int *
will make the types compatible, so the compiler won't emit a peep. But the code is dangerously wrong! In fact, on an Alpha machine it could fail: there, sizeof(int) == 4
, whereas sizeof(void *) == 8
. So you're telling the compiler to leave 4 bytes on the stack; as soon as you return from the current function, your program will die horribly.
Without the cast, of course, you're assigning an int
to an int *
, which yields a warning (at least). And we've seen that the warning is not spurious, but very real.
So...
DON'T CAST THE RETURN VALUE OF malloc()
.
Nowadays, this abomination is coming back into trend, since the cast is required in a different language, C++. This, of course, has no bearing on correct C code (see a C program which is not a C++ program).