I was looking at Do I cast the result of malloc? and it appears that you should not cast the result in pure c code because it's potentially hides bugs and is redundant. But I also see people saying that c++ requires the cast, so should all c libraries cast the result of malloc because they could realistically be used in a c++ project?
-
Why would you use `malloc` in c++? It has a nice `new` keyword. – Eugene Sh. Mar 04 '15 at 19:43
2 Answers
it appears that you should not cast the result in pure c code because it's potentially hides bugs and is redundant
That is correct.
shouldn't all c libraries cast the result of malloc because they could realistically be used in a c++ project?
No. A C library can be used from within a C++ project but still be compiled as C.

- 135,547
- 38
- 252
- 361
No. If it's C code, it should be compiled as C, not as C++, and thus the compiler will allow the implicit cast from void*
to some other pointer.
It is only when malloc
is used in C++ code that you need to cast it - and it's in my view a "bad smell" - in other words, a sign that the code should be modernized to use new
or vector
or something along those lines. (Of course, there are valid reasons for doing this - for example, you could have some 10k lines of useful code, that you need to plumb into a C++ framework for something else - but typically, the best approach then is to write some C++ bindings that interface to those 10k lines and keep compiling that as C)

- 126,704
- 14
- 140
- 227