Friday 24 March 2017

c - is it necessary to type-cast malloc and calloc






Possible Duplicate:
Do I cast the result of malloc?







I was googling to find out the reason for type-casting of malloc and calloc. But, i only found type-casting of malloc is not necessary since it return void pointer but, what about calloc. This is the same reason for calloc too ???



Now, if we move back to first point, about return value of malloc and calloc. Then, i found that, both are returning the allocated spaces. So, i'm little bit confused here. So, my questions are





  1. What is the return value of malloc and calloc


  2. Is it necessary to type-cast malloc and calloc. And why ?





Answer




What is the return value of malloc and calloc?




It is a pointer to void (void*).




Is it necessary to type-cast malloc and calloc. And why ?





No, because the conversion from a pointer to void to a pointer to object is implicit.




C11 (n1570), § 6.3.2.3 Pointers
A pointer to void may be converted to or from a pointer to any object type.




It is right for both malloc and calloc.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...