I have always been curious about this - why do in C++ I have to cast return value from malloc
but not in C?
Here is the example in C++ that works:
int *int_ptr = (int *)malloc(sizeof(int*));
And here is the example in C++ that doesn't work (no cast):
int *int_ptr = malloc(sizeof(int*));
I heard that in C, in fact, casting an output from malloc()
is a mistake.
Can anyone comment on this topic?
Several points:
C allows void pointers to be implicitly converted to any other object pointer type. C++ does not.
Casting the result of malloc()
in C will supress a useful diagnostic if you forget to include stdlib.h or otherwise don't have a declaration for malloc()
in scope. Remember that if C sees a function call without a prior declaration, it will assume that the function returns int
. If you don't have a declaration for malloc()
and you leave off the cast, you'll get a diagnostic to the effect that you're trying to assign incompatible types (int to pointer). If you cast the result, you supress the diagnostic and will potentially have runtime issues, since it's not guaranteed that converting a pointer value to an int and back to a pointer again will give you a useful result.
If you're writing C++, you should be using new
and delete
instead of malloc()
and free()
. Yeah, yeah, yeah, I've heard all the reasons why people want their code to compile as both C and C++, but the benefits of using the right memory management tool for the language outweigh the cost of maintaining two versions IMO.
Note: the void *
type was added in the C89 standard; earlier versions of C had malloc()
return char *
, so in those versions the cast was required if you were assigning the result to a different pointer type. Almost everybody supports at least the C89 standard though, so the odds of you running into one of those older implementations is very, very low.