2

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?

1
  • Why would you use malloc in c++? It has a nice new keyword. Commented Mar 4, 2015 at 19:43

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.