What are issues if we mix new and free in C++?

(Last Updated On: August 17, 2016)

Answer: new and free in c++ should never be mixed or else we may get memory leak issues and resource leak issues and may take extra effort and time to maintain the C++ software project.Memory leak really a not a good elements for software and cause poor performance to a software.

 

Recommended to read another interview question i.e.  issues due to memory leaks in C++ software project.

 

1- Memory & resources leak
We should stick to use new and delete for dynamic memory allocation and de-allocation respectively in C++ program. Mixing new and free is not a good idea, as C++ new operator calls the constructor and delete operator calls destructor of a class.
If we use free, it will not call destructor of a class. You might have made some de-allocation and resource clean-up in class destructor. So, memory and resources will be leaked, that will drastically affect performance of the application.

Sample code:

In the output, notice that when we call delete ptr, destructor gets called and resource cleanup is happening while in case of free(ptr)there is no destructor call hence missing resource cleanup.

 

2-May require extra efforts and time during project development/maintenance.

 

If no memory de-allocation and resource clean-up is happening in destructor of a class in C+, then we can use free() function instead of delete operator in C++. But, as a best practice we should always use delete operator to deallocate memory, so it can call destructor of a class.

Assume, at some later point of time during project development and maintenance, if some other new programmer comes and put memory de-allocation and resource clean-up code in destructor of the class then application will be in trap as on using free() desturctor will not be called resulting no cleanup. A programmer has to find all related free () functions in the project and replace with delete operator in c++ and test.

So, avoid extra efforts and time by not mixing new and free in C++ program.