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

强颜欢笑 提交于 2019-11-28 00:59:49

问题


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 ?


回答1:


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.




回答2:


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




回答3:


The return value of malloc and calloc is a void*. The address of the heap memory space allocated by these functions.

Both functions allocate memory. The only difference between them is that

  • malloc simply allocates memory.
  • calloc allocates the memory and initializes it to 0.

In C its not recommended to cast the return value of these functions.

In C++ it is mandatory to cast.




回答4:


What is the return value of malloc() and calloc()?

void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);

void* is returned by both the functions.

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

No. It is not required to typecast. The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. 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.



来源:https://stackoverflow.com/questions/13287888/is-it-necessary-to-type-cast-malloc-and-calloc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!