Why Cast malloc Returns in C – Explained

c++heap-memorymalloc

    int length = strlen(src);
    char *structSpace = malloc(sizeof(String) + length + 1);
    String *string = (String*) structSpace;    
    int *string = (int*) structSpace;

*I created a struct called String

Best Answer

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.

Related Question