Why do we need to cast what malloc returns?

后端 未结 7 1841
情歌与酒
情歌与酒 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:19

    You should strongly consider casting after using the malloc command because it provides for greater portability and greater compatibility with other parts of your program. If you do not do so, you may run the risk of incompatible data types which could result in errors.

    0 讨论(0)
  • 2020-12-10 18:21

    The C FAQ list is an invaluable resource: Why does some code carefully cast the values returned by malloc to the pointer type being allocated?.

    0 讨论(0)
  • 2020-12-10 18:22

    You tend to see this kind of C code from novices (or C++ coders :-) ):

    int main() {
        int len = 40;
        char *my_string = (char *) malloc(sizeof(char)*len);
        return 0;
    }
    

    This is unnecessary and evil, you can avoid the useless cast via including stdlib.h

    #include <stdlib.h>
    int main() {
        int len = 40;
        char *my_string = malloc(sizeof(char)*len);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-10 18:24

    Because malloc returns a pointer to void, i.e., it is simply allocating chunks of memory with no regard as to the data that will be stored there. In C++ your returned void* will not be implicitly cast to the pointer of your type. In your example, you have not cast what malloc has returned. Malloc returned a void* which was implicitly cast to a char*, but on the next line you... ok, it doesn't make much sense anymore.

    0 讨论(0)
  • 2020-12-10 18:29

    This is one of the few issues that makes the statement "C++ is a superset of C" not completely true. In C, a void pointer can be implicitly cast to any other type of pointer. However, C++ is a bit more strict with type safety, so you need to explicitly cast the return value of malloc to the appropriate type. Usually, this isn't much of an issue, because C++ code tends to use new rather than malloc, which doesn't require typecasting.

    0 讨论(0)
  • 2020-12-10 18:34

    You don't. void* will implicitly cast to whatever you need in C. See also the C FAQ on why you would want to explicitly avoid casting malloc's return in C. @Sinan's answer further illustrates why this has been followed inconsistently.

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