Open In App

What happens if we mix new and free in C++?

Improve
Improve
Like Article
Like
Save
Share
Report

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;

It will create a memory location for type int and returns its address. free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

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:

C++




// C++ program to illustrate the working
// of memory allocation if new and free
// are mixed
#include <iostream>
using namespace std;
  
class A {
private:
    int* p;
  
public:
    // Default Constructor
    A()
    {
        cout << "Constructor is executed"
             << endl;
        p = new int;
        *p = 5;
    }
  
    // Destructor
    ~A()
    {
        cout << "Destructor is executed"
             << endl;
        // resource clean-up
        cleanup();
    }
  
    // Member Function
    void cleanup()
    {
        cout << "Resource clean-"
             << "up completed" << endl;
    }
  
    // Function to display the value
    // of class variables
    void display()
    {
        cout << "value is: "
             << *p << endl;
    }
};
  
// Driver Code
int main()
{
    // Create Object of class A
    A* ptr = new A();
    ptr->display();
  
    // Destructor will be called
    delete ptr;
  
    A* ptr1 = new A();
    ptr1->display();
  
    // No destructor will be called
    // hence no resource clean-up
    free(ptr);
  
    return 0;
}


Output:

Constructor is executed
value is: 5
Destructor is executed
Resource clean-up completed
Constructor is executed
value is: 5

Explanation:

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.



Last Updated : 22 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads