Monday, 27 June 2016

Typecasting malloc C++





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));

Answer




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:




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...