Needless pointer-casts in C

前端 未结 12 739
刺人心
刺人心 2020-12-09 10:05

I got a comment to my answer on this thread:

Malloc inside a function call appears to be getting freed on return?

In short I had code like this:



        
12条回答
  •  孤街浪徒
    2020-12-09 10:47

    The "forgot stdlib.h" argument is a straw man. Modern compilers will detect and warn of the problem (gcc -Wall).

    You should always cast the result of malloc immediately. Not doing so should be considered an error, and not just because it will fail as C++. If you're targeting a machine architecture with different kinds of pointers, for example, you could wind up with a very tricky bug if you don't put in the cast.

    Edit: The commentor Evan Teran is correct. My mistake was thinking that the compiler didn't have to do any work on a void pointer in any context. I freak when I think of FAR pointer bugs, so my intuition is to cast everything. Thanks Evan!

提交回复
热议问题