I have some C code with malloc statements in it that I want to merge with some C++ code.
I was wondering when and why is typecasting a call to malloc neccessary in C++?
For example:
char *str = (char*)malloc(strlen(argv[1]) * sizeof(char));
No, type-casting malloc ’s return value is absolutely unnecessary and is often a sign of ignorance. The issue is not specific to malloc, it’s about casting a void pointer to a pointer of other type, which is allowed in C. Note that the return value of malloc is void*. int *q = p; // implicit type cast from void * to int * is allowed!
Typecasting is a way to convert variables, constants or expression from one type to another type. Conversion from one type to another is often required in programming. Consider a case where you want to find average of three numbers. Let us write a program to find average of three numbers.
Explicit typecasting is manual type conversion from one type to another type. In explicit cast we have full control over the conversion. Explicit conversion can be performed bi-directional i.e. you can cast both a lower type to higher as well as a higher type to lower.
Implicit type casting is under the control of the compiler. So a programmer no needs to be considered about the implicit type casting process. Let us see an example for a better understanding. The type conversion performed by the programmer by posing the data type of the expression of a specific type is known as explicit type conversion.
when and why is typecasting a call to malloc neccessary in C++?
Always when not assigning to a void *
, since void *
doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever use malloc
in C++ in the first place.
I am not suggesting you should use new
instead of malloc
. Modern C++ code should use new
sparingly, or avoid it altogether if possible. You should hide all use of new
or use non-primitive types (like std::vector
mentioned by Xeo). I'm not really qualified to give advice in this direction due to my limited experience but this article along with searching for "C++ avoid new" should help. Then you'll want to look into:
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