Wednesday 21 August 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...