new vs malloc() and delete vs free() in C++
new and malloc() can both allocate dynamic memory, but they are not equivalent.
malloc() and free() are the library functions provided by the C which can be used to allocate and deallocate memory at runtime, whereas new and delete are the operators provided by C++ which can be used to allocate and deallocate memory at runtime.
The basic difference between new and malloc() is that memory allocation using new allocates storage and calls the constructor which initializes the memory. In case of malloc(), returned memory is uninitialized and needs to be initialized explicitly.
Similarly, deallocating memory using delete calls the destructor and hence allowing to do a proper cleanup whereas in case of free(), destructors are not called and hence cleanup needs to be done prior free() call.
For normal C++ application code, prefer automatic storage, standard containers, and smart pointers where possible. Use malloc() mainly when working with C APIs or low-level memory-management code.
Let’s look into some more difference between these functions.