9

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 ?

Community
  • 1
  • 1
Ravi
  • 30,829
  • 42
  • 119
  • 173
  • @hmjd may be.. but here i'm asking for both `malloc` and `calloc` too. – Ravi Nov 08 '12 at 11:16
  • Yes, this is a duplicate, but compilers are getting more pissy about requiring you to cast the void pointer to any other type - which flies in the face of the original purpose of a void pointer, that is was a universal type that could be cast and assigned to anything. This is more C "progress". – user2548100 Jan 16 '14 at 17:29

4 Answers4

12

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.

md5
  • 23,373
  • 3
  • 44
  • 93
3

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

Omkant
  • 9,018
  • 8
  • 39
  • 59
1

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.

fuz
  • 88,405
  • 25
  • 200
  • 352
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
1

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.

sgarizvi
  • 16,623
  • 9
  • 64
  • 98