Why does C++ require a cast for malloc() but C doesn't?

Viewed 11059

I have always been curious about this - why do in C++ I have to cast return value from malloc but not in C?

Here is the example in C++ that works:

int *int_ptr = (int *)malloc(sizeof(int*));

And here is the example in C++ that doesn't work (no cast):

int *int_ptr = malloc(sizeof(int*));

I heard that in C, in fact, casting an output from malloc() is a mistake.

Can anyone comment on this topic?

4 Answers

C has very lax type rules and C++ has somewhat stricter rules. The difference in this case is that C allows implicit conversion/assignment between object pointers and void pointers. C++ does not.

In fact old style C even encouraged implicit conversion to/from void pointers, as part of old style generic C programming. C++ never needed void pointers for such, since it got function overloading and templates etc. Using void pointers in C++ is often fishy.

Regarding beating the dead horse debate about casting the result of malloc causing bugs in case stdlib.h wasn't included, doing so has never been valid C++ and it has not been valid C either for the past 21 years.

Best practices:

C

  • If you are compiling with -std=c89, -ansi or -dinosaur etc, then don't cast.
  • Otherwise, follow your coding standard.
    • If it allows implicit conversions between void and object pointers, don't cast.
    • If it doesn't allow it, then do cast (this probably implies you are using static code analysis).
    • If you have no coding standard, then it really doesn't matter much. The cast is harmless but adds clutter.

C++

  • Always cast.
  • Avoid void pointers.
  • Most importantly, avoid malloc and use new/new[] instead.
Related