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.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- what happens when you don't free memory after using malloc()
- new vs malloc() and free() vs delete in C++
- What happens if loop till Maximum of Signed and Unsigned in C/C++?
- new vs operator new in C++
- What happens when more restrictive access is given to a derived class method in C++?
- What happens when a virtual function is called inside a non-virtual function in C++
- delete and free() in C++
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- How does free() know the size of memory to be deallocated?
- How to deallocate memory without using free() in C?
- Program for Deadlock free condition in Operating System
- new and delete operators in C++ for dynamic memory
- C++ | new and delete | Question 1
- C++ | new and delete | Question 2
- C++ | new and delete | Question 3
- C++ | new and delete | Question 4
- C++ | new and delete | Question 5
- Overloading New and Delete operator in c++
- C++17 new feature : If Else and Switch Statements with initializers
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.