Is typecast required in malloc? [duplicate]

2019-01-12 04:18发布

This question already has an answer here:

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

标签: c casting malloc
5条回答
乱世女痞
2楼-- · 2019-01-12 04:43

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-12 04:45

Just because malloc returns a void* and since void* has not defined size you can't apply pointer aritmetic on it. So you generally cast the pointer to the data type your allocated memory block actually points.

查看更多
做自己的国王
4楼-- · 2019-01-12 04:55

The answers are correct, I just have an advice:

  • don't play with pointers - which malloc() returns - too much, cast them to a specified type asap;
  • if you need to do some math with them, cast them to char*, so ptr++ will mean what you except: add 1 to it (the size of the datatype will be added, which is 1 for char).
查看更多
戒情不戒烟
5楼-- · 2019-01-12 04:57

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.

查看更多
▲ chillily
6楼-- · 2019-01-12 05:06

You're not required to cast the return value of malloc. This is discussed further in the C FAQ: http://c-faq.com/malloc/cast.html and http://c-faq.com/malloc/mallocnocast.html .

查看更多
登录 后发表回答