As we know that new is used to create memory dynamically and it is the programmer’s responsibility to delete the memory location explicitly and it is deleted by using the delete keyword. The syntax for creating memory at runtime using new keyword:
int *ptr = new int;
What happens if we mix new and free in C++?
We know that memory created by new keyword is deleted by using the delete keyword and memory created by malloc() is deleted by free(). new calls the constructor and delete calls the destructor for memory deallocation. Now, creating memory using new keyword and try to delete it using free() then the destructor will not be called and because of that memory and resources will not be free. And it will lead to memory and resources leak. Below is the program to analyze how free() and delete behaves:
Constructor is executed value is: 5 Destructor is executed Resource clean-up completed Constructor is executed value is: 5
In the above code, an object is created using new Keyword, and we are trying to delete this object using free(). It will not call the destructor for this object, and memory and resources of this object will not release. So, It is always suggested avoiding extra efforts and time by not mixing new and free in C++ program.