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

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 interview question read: What are issues due to memory leaks in C++ software applications?

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:

#include 
using namespace std;

class A{
private:
	int *p;

public:
	A(){
		cout<<"Constructor!!!\n";
		p = new int;*p=5;
	}
	~A(){
		cout<<"Destructor!!!,Cleaning resources\n";
		//resource clean-up
		cleanup();
	}
	void cleanup(){
		cout<<"resource cleanup done!!!"<<endl;
	}
	void display(){
		cout<<"value is: "<<*p<<"\n"; 	} }; int main(){ 	A *ptr = new A(); 	ptr->display();
	delete ptr;// calls destructor, hence resource cleanup

	A *ptr1 = new A();
	ptr1->display();
	free(ptr); // no destructor will be called, so, no resource cleanup


	return 0;
}
Output:
       Constructor!!!
       value is: 5
       Destructor!!!,Cleaning resources
       resource cleanup done!!!
       Constructor!!!
       value is: 5

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.



Leave a Comment