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));
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));
Always when not assigning to a
void *
, sincevoid *
doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever usemalloc
in C++ in the first place.I am not suggesting you should use
new
instead ofmalloc
. Modern C++ code should usenew
sparingly, or avoid it altogether if possible. You should hide all use ofnew
or use non-primitive types (likestd::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:malloc
always returns avoid*
so you need to cast everything (because C++ has stronger type checking than C and don't this automatically)When I am using C, I also cast everything, for code clarity.
Also, feel free to keep using
malloc()
in C++, it is there for a good reason.Converting all the C code to C++ by rewriting every single
malloc()
to new is very prone to introduce lots of errors in your code, unless you have the time to keep reading the code you are merging to find every single instance ofmalloc()
,free()
,calloc()
, etc... on it.Just don't mix
malloc()
withdelete
ornew
withfree()
or things break.Compile your C library. Compile your C++ library. Make them play nice in whatever "main" program that uses them. Point is if your maintaining a mixed code base, you probably want to isolate the pure C stuff from the C++ stuff. Otherwise your C stuff turns into C++ stuff that only looks like C.
If you can change that code its probably better to use
new
instead so it would look like thischar* str = new char;
this means you don't need to do any casting like the C way and you don't need to specify how large the memory you need. Also if this was an object like a
std::string
then you WILL not call the constructor when you usemalloc
, this merely reserves the memory for use with the pointerstr
so best always usenew
with C++ if you can also when you reclaim memory always use the appropriate way, if younew
then youdelete
and if youmalloc
youfree
. If you usefree
on memory that has beennew
'd then you won't call that objects destructor.First, in almost all circumstances just don't use
malloc
in a C++ program, but prefernew
instead because it will make sure that constructors are called when needed, etc.However if for legacy reasons you're trying to avoid as much rewrite as possible - you'll need to cast any
malloc
call that's not assigned to avoid*
pointer.