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

假装没事ソ 提交于 2019-11-29 07:22:04

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.

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

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.

Jeyaram

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.

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