In C++, it’s standard to always use new over malloc(). However, in this question, the most portable way of overloading the new operator while avoiding platform specific code is to place a call to malloc() within it to do the actual allocation.
When overloaded, constructors are called and type-safety is kept. In addition, you can monitor and control how memory is allocated.
My question, when used in this capacity, are there still any downsides to using malloc() within C++?
The biggest downside I can think off is you can’t explicitly call
deleteordelete []on a pointer that has been allocated usingmalloc()without invoking undefined behavior. If you are going to go the highly un-recommended path and usemalloc()to allocate memory explicitly for C++ objects, then you are still going to have to callplacement newin order to properly call a constructor to initialize the memory location allocated bymalloc(). Without anoperator newwrapper onmalloc(), you’ll also have to test to make sure you do not get aNULLreturn value, and create some code to handle cases where you do without the benefit of throwing an exception. It’s also very dangerous, and can incur a number of undefined behaviors, if you simply tried to use C-library functions likememcpy()to copy C++ objects into heap memory allocated withmalloc().Furthermore, because you utilized
placement newfor your object construction, you are going to have to explicitly call the destructuors for your dynamically allocated objects, and then explicitly callfree()on the pointers. This again can cause all sorts of problems if it’s not handled correctly, especially if you wanted to work with polymorphic types and virtual base-classes.If you are going to work with just
malloc()andfree(), a nice rule of thumb to avoid undefined behavior pitfalls is to keep the objects you allocate and deallocate withmalloc()andfree()to POD-types. That means non-polymorphic structs or classes with no user-defined constructors, destructors, copy-constructors, assignment operators, private/protected non-static data-members, or base-classes, and all the non-static data-members of the struct/class are POD-types themselves. Since POD-types are basically C-style structs (but with the added ability to define non-static methods and athispointer), you can safely do C-style memory management with them.