devxlogo

New & Malloc

New & Malloc

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist