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).

Casting the return value of malloc will save you from coding mistakes along the lines of:

#define ENTRIES 10
int i;
double **val;

val = (double **) malloc(ENTRIES*sizeof(double *));
for(i = 0 ; i < ENTRIES ; i++)
        val = (double *) malloc(sizeof(double)); /* OOOPS */
Blowing away previously allocated pointers is a bad idea. In the above code, the compiler should alert you of the type mismatch and error out. Leave the cast out, and it will compile with no trouble and you'll be chasing the crazy segmentation fault for the next 30 minutes.

Log in or register to write something here or to contact authors.