It can still be necessary to use malloc
and free
in C++ when you are interacting with APIs specified using plain C, because it is not guaranteed to be safe to use free
to deallocate memory allocated with operator new
(which is ultimately what all of the managed memory classes use), nor to use operator delete
to deallocate memory allocated with malloc
.
A typical example is POSIX getline
(not to be confused with std::getline
): it takes a pointer to a char *
variable; that variable must point to a block of memory allocated with malloc
(or it can be NULL, in which case getline
will call malloc
for you); when you are done calling getline
you are expected to call free
on that variable.
Similarly, if you are writing a library, it can make sense to use C++ internally but define an extern "C"
API for your external callers, because that gives you better binary interface stability and cross-language interoperability. And if you return heap-allocated POD objects to your callers, you might want to let them deallocate those objects with free
; they can't necessarily use delete
, and making them call YourLibraryFree
when there are no destructor-type operations needed is unergonomic.
It can also still be necessary to use malloc
when implementing resizable container objects, because there is no equivalent of realloc
for operator new
.
But as the other answers say, when you don't have this kind of interface constraint tying your hands, use one of the managed memory classes instead.