Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I cast the result from malloc?

Tags:

c

malloc

The following code gives the error "error: invalid conversion from void* to char* [-fpermissive]"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
    char *t = malloc(20);
}

However, casting the result of malloc solves the problem. But I cannot understand why as this question says that casting the result of malloc is not needed.

like image 336
Nikunj Banka Avatar asked May 29 '13 13:05

Nikunj Banka


People also ask

Why do you need to cast malloc?

You don't cast the result of malloc , because doing so adds pointless clutter to your code. The most common reason why people cast the result of malloc is because they are unsure about how the C language works.

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 .

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 is typecasting necessary in C?

We can use the process of type casting to convert the character (char) data type to the int (integer) data type in C. When we are performing a conversion between these two, the resultant value would be an integer (int) data type. It is because the int data type is comparatively bigger than the char data type in C.


1 Answers

You compiled this C program using a C++ compiler. It is necessary to cast the result of malloc in C++, but not in C.

like image 78
zwol Avatar answered Sep 28 '22 10:09

zwol