Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why malloc return void pointer?
Because we can typecast any data-type into any another data type,then if malloc return int type pointer then also we can typecast it into another data type pointer,then why return void pointer?
Posted
Updated 11-Mar-13 0:21am
v2
Comments
CPallini 11-Mar-13 6:50am    
Because void * is C's 'generic' :-)

The reason is that malloc has no clue as to what data type you are really allocating; it just allocates raw memory. Returning a void* guarantees that you cast the pointer to something useful. Returning any other pointer type would risk that you forget to cast the pointer to what it really points to.

Btw: int would be a very bad choice for the return value as it isn't even a pointer. It is not guaranteed that a pointer value will fit into an int (for example that is so on many 64-bit architectures). Treating an int and a pointer as basically the same is a common error that many C beginners make. And some legacy code also shows this bad habit.
 
Share this answer
 
Comments
CPallini 11-Mar-13 6:52am    
My 5.
Please note the OP would prefer an (int *) return type (not an int).
nv3 11-Mar-13 7:36am    
Thanks! Oops, I should have read the question more thoroughly.
There are two reasons, first, malloc doesn't know why you need memory. So it just return number of bytes asked to return. Secondly (I am not sure this is purposefully done for this reason) you cannot dereference void * easily so it can help you to avoid accidents.
 
Share this answer
 
Comments
CPallini 11-Mar-13 6:52am    
My 5+.
BaldevS 11-Mar-13 7:50am    
i got it..thnks 4 it..
[no name] 11-Mar-13 6:57am    
Thanks CPallini.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900