Why do we need to cast what malloc returns?

后端 未结 7 1856
情歌与酒
情歌与酒 2020-12-10 18:04
    int length = strlen(src);
    char *structSpace = malloc(sizeof(String) + length + 1);
    String *string = (String*) structSpace;    
    int *string = (int*) s         


        
相关标签:
7条回答
  • 2020-12-10 18:36

    In C, casting the result from malloc is unnecessary and should not be done. Doing so can, for example, cover up the error of having failed to #include <stdlib.h>, so you don't have a prototype for malloc in scope. This, in turn, can lead to other errors and lack of portability (though the worst offenders in that respect are now mostly obsolete).

    In C++, you must cast the result of malloc to assign it to a pointer to any type other than void. Unless you really need to write code that can be compiled as either C or C++, however, you should generally avoid using malloc in C++ at all and allocate memory using new.

    0 讨论(0)
提交回复
热议问题