This question already has an answer here:
- Do I cast the result of malloc? 26 answers
What is the use of typecast in malloc? If I don't write the typecast in malloc then what will it return? (Why is typecasting required in malloc?)
This question already has an answer here:
What is the use of typecast in malloc? If I don't write the typecast in malloc then what will it return? (Why is typecasting required in malloc?)
You should never cast the return value of
malloc()
, in C. Doing so is:void *
is compatible with any other pointer type (except function pointers, but that doesn't apply here).So: there are no benefits, at least three drawbacks, and thus it should be avoided.
Just because malloc returns a
void
* and sincevoid*
has not defined size you can't apply pointer aritmetic on it. So you generally cast the pointer to the data type your allocated memory block actually points.The answers are correct, I just have an advice:
I assume you mean something like this:
int *iptr = (int*)malloc(/* something */);
And in C, you do not have to (and should not) cast the return pointer from
malloc
. It's avoid *
and in C, it is implicitly converted to another pointer type.int *iptr = malloc(/* something */);
Is the preferred form.
This does not apply to C++, which does not share the same
void *
implicit cast behavior.You're not required to cast the return value of
malloc
. This is discussed further in the C FAQ: http://c-faq.com/malloc/cast.html and http://c-faq.com/malloc/mallocnocast.html .