malloc()
return a void*
, as malloc()
does not know how its caller will be using the memory it allocated on the heap.
So it's up to you, the caller to cast the (void*)
, into the appropriate type of pointer, that you want to use inside the memory.
(int*)
to store integers.
(char*)
to store characters etc..
Having said so, you don't have to explicitly cast the return of a malloc()
call. And in some cases, doing so may result in bugs.
Kindly read up the issue here
What's wrong with casting malloc's return value?
Specifically, what's dangerous about casting the result of malloc?