new vs malloc() in C++: Key Differences & When to Use

new is the C++ operator that allocates memory and calls constructors; malloc() is the old C library function that just grabs raw bytes and returns a void pointer.

Junior devs often copy-paste C snippets into C++ files, see both compile, and assume they’re interchangeable. The silent difference? new can throw, initialize objects, and be overridden; malloc() can’t. Legacy tutorials muddy the waters further.

Key Differences

new invokes constructors, returns typed pointers, and throws std::bad_alloc. malloc() returns void*, needs casting, and sets errno. Only new[]/delete[] pair with arrays; malloc()/free() ignore object lifetimes.

Which One Should You Choose?

In modern C++, favor new for objects so RAII and exceptions work. Use malloc() only when integrating with pure C APIs or writing low-level memory pools where you manually manage construction.

Examples and Daily Life

Creating a std::string* with new gives you a ready-to-use string; with malloc(sizeof(std::string)) you just get uninitialised bits that crash on first access unless you call placement new.

Can malloc() call constructors?

No. You must use placement new to run constructors on malloc()-ed memory.

Is new slower than malloc()?

Often new is implemented on top of malloc() plus constructor overhead; the difference is tiny compared to cache misses.

Can I mix new/free or malloc/delete?

Never. Mismatched pairs cause undefined behaviour—crashes or memory corruption.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *