Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it necessary to type-cast malloc and calloc [duplicate]

Tags:

c

malloc

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 ?

like image 838
Ravi Avatar asked Nov 08 '12 11:11

Ravi


People also ask

Is it necessary to type cast malloc?

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.

What is the return type of malloc () or calloc ()?

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.

What is the return type of malloc () in C?

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()

Does calloc take more time than 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.


2 Answers

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.

like image 191
md5 Avatar answered Sep 23 '22 13:09

md5


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

like image 25
Omkant Avatar answered Sep 22 '22 13:09

Omkant