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
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.
struct node*-typecasting is needed since malloc() returns a void pointer to starting address of memory block ,but we need pointer to node.
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.
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 .
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.
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.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With