Question:
I understand that most of the time, new and malloc may use the same allocation routines, but does that necessarily mean new calls malloc? I am asking because I want to see all the memory being allocated in my program, but I use both new and malloc. If it’s possible, I would like to just overwrite malloc instead of both malloc and new.
Answer:
The C++ standard doesn’t specify whether new calls malloc() to allocate raw memory. It’s implementation-dependent. Some compilers may use malloc() as the underlying allocation routine whereas others use a different allocation routine. Therefore, it’s best not to assume that new calls malloc() because even if it’s the case, future releases of your compiler might use a different allocation routine. Instead, define your own version of malloc() and have your custom operator new call it.