Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typecast required in malloc? [duplicate]

Tags:

c

casting

malloc

What is the use of typecast in malloc? If I don't write the typecast in malloc then what will it return? (Why is typecasting required in malloc?)

like image 351
user615929 Avatar asked Feb 14 '11 14:02

user615929


2 Answers

I assume you mean something like this:

int *iptr = (int*)malloc(/* something */);

And in C, you do not have to (and should not) cast the return pointer from malloc. It's a void * and in C, it is implicitly converted to another pointer type.

int *iptr = malloc(/* something */);

Is the preferred form.

This does not apply to C++, which does not share the same void * implicit cast behavior.

like image 73
逆さま Avatar answered Sep 19 '22 22:09

逆さま


You should never cast the return value of malloc(), in C. Doing so is:

  • Unnecessary, since void * is compatible with any other pointer type (except function pointers, but that doesn't apply here).
  • Potentially dangerous, since it can hide an error (missing declaration of the function).
  • Cluttering, casts are long and often hard to read, so it just makes the code uglier.

So: there are no benefits, at least three drawbacks, and thus it should be avoided.

like image 40
unwind Avatar answered Sep 19 '22 22:09

unwind