I've seen a lot of the following in older C code:
type_t *x = (type_t *) malloc(...);
What's the point of casting the pointer returned from malloc()
since it's void *
? Is it because older C compilers didn't support void pointers and malloc()
used to return char *
instead?
Quite the contrary. You need to cast a void pointer to an actual type before you can use it, because a
void *
signifies nothing about the data stored at that location.I'm not aware that malloc ever returned a char*.
But implicit casting from void* to type_t* (or any other type) hasn't always been allowed. Hence, the need to explicitly cast to the proper type.
Your own explanation is the right one. Pre-ANSI C ('K&R' C) did not have a
void *
type with implicit conversion.char *
doubled as a pseudovoid *
type, but you needed the explicit conversion of a type cast.In modern C the casting is frowned upon because it can suppress compiler warnings for a missing prototype of
malloc
. In C++, the casting is needed (but there you should be usingnew
instead ofmalloc
most of the time).Update
My comments below that try to explain why the cast is required were a bit unclear, I'll try to explain it better here. You might think that even when
malloc
returnschar *
, the cast is not needed because it is similar to:But in this example a cast is also needed. The second line is a constraint violation for the simple assignment operator (C99 6.5.1.6.1). Both pointer operands need to be of compatible type. When you change this to:
the constraint violation disappears (both operands now have type
char *
) and the result is well-defined (for converting to a char pointer). In the 'reverse situation':the same argument hold for the cast, but when
int *
has stricter alignment requirements thanchar *
, the result is implementation defined.Conclusion: In the pre-ANSI days the type cast was necessary because
malloc
returnedchar *
and not casting results is a constraint violation for the '=' operator.The problem here is not compatibility with any dialect of C. The problem is C++. In C++, a void pointer cannot be automatically converted to any other pointer type. So, without an explicit cast, this code would not compile with a C++ compiler.