Is it a better practice to typecast the pointer returned by malloc?

后端 未结 7 2182
闹比i
闹比i 2020-12-10 19:30

For the C code below, compare the defintions of the int pointers a and b;

#include 
#include 

int main()
{
  int *a=malloc(s         


        
7条回答
  •  失恋的感觉
    2020-12-10 20:18

    No, Yes, Never

    • Some people cast the pointer, I don't.
    • Yes, the type conversion happens "automatically"
    • It is never necessary in C.
    • In a strange way, casting the result compromises C++ portability. A module referenced from C++ will most likely be compiled as C, in which case it won't matter. But if the code is somehow copy-and-pasted into C++, I think you want each such line flagged, as a line of code calling malloc() in C++ is a suspicious LoC.
    • In part this is a holdover from early K&R C that had no such type as void, so malloc() returned a char *. Now, you needed to do the cast. Consequently the design pattern of casting malloc() developed and influenced all the people who wrote the next set of code, and people are stilling reading those code bodies today and carrying the pattern forward. But C89 had void and so it's time to streamline the code.
    • Depending on exactly how it is done, the cast may violate DRY (aka DIE.) As Chris Lutz points out, it unnecessarily reduces the level of abstraction. Since that isn't exactly sky-high in a C program to start with, I would prefer not to lose the level we do have.

提交回复
热议问题