Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting malloc C++ [duplicate]

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));
like image 505
user2052561 Avatar asked Feb 27 '13 17:02

user2052561


People also ask

Can you type cast malloc's return value?

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!

What is typecasting in C++?

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.

What is explicit typecasting in Java?

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.

What is implicit type casting?

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.


1 Answers

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:

  • std::alocator
  • Smart pointers
like image 112
cnicutar Avatar answered Oct 02 '22 16:10

cnicutar