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
What is the return value of malloc and calloc
Is it necessary to type-cast malloc and calloc. And why ?
In C, you don't need to cast the return value of malloc . The pointer to void returned by malloc is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed.
The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type. On error, these functions return NULL. NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero.
The malloc() function returns a pointer to the reserved space. The storage space to which the return value points is suitably aligned for storage of any type of object. The return value is NULL if not enough storage is available, or if size was specified as zero. Example that uses malloc()
Calloc is slower than malloc. Malloc is faster than calloc. It is not secure as compare to calloc. It is secure to use compared to malloc.
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 tovoid
may be converted to or from a pointer to any object type.
It is right for both malloc
and calloc
.
malloc()
or calloc()
returns void *
which can be assigned to any pointer type .In C it's not necessary to typecast the void*
since it's implicitly done by compiler.But in c++ it will give you error if you won't typecast
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With