Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to cast what malloc returns?

    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

like image 504
user133466 Avatar asked Oct 27 '09 22:10

user133466


People also ask

Why are you casting the return value of malloc?

The cast allows for pre-1989 versions of malloc that originally returned a char * . Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call.

Why do we need to type cast malloc?

struct node*-typecasting is needed since malloc() returns a void pointer to starting address of memory block ,but we need pointer to node.

Why is it needed to type cast the return address of a dynamically allocated memory?

realloc() function need to be type casted because the address returned by the realloc() does not represent any data type. realloc() function may change the address of the previously allocated block, so it is recommended to store the new address in pointer or use some new pointer to store the reallocated address.

Why do we need to typecast while calling malloc () and calloc ()?

It is not required to typecast. The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL .


3 Answers

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.

like image 77
Andrew Coleson Avatar answered Oct 17 '22 17:10

Andrew Coleson


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.

like image 6
Ed S. Avatar answered Oct 17 '22 17:10

Ed S.


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?.

like image 6
Sinan Ünür Avatar answered Oct 17 '22 17:10

Sinan Ünür