delete and free() in C++
delete and free() in have similar functionalities programming languages but they are different. In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
Differences in delete and free are:
delete() | free() |
|---|---|
| It is an operator. | It is a library function. |
| It de-allocates the memory dynamically. | It destroys the memory at the runtime. |
| It should only be used either for the pointers pointing to the memory allocated using the new operator or for a NULL pointer. | It should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. |
| This operator calls the destructor after it destroys the allocated memory. | This function only frees the memory from the heap. It does not call the destructor. |
| It is faster. | It is comparatively slower than delete as it is a function. |
Note: The most important reason why free() should not be used for de-allocating memory allocated using new is that, it does not call the destructor of that object while delete operator does.
Example for delete operator:
CPP
// CPP program to demonstrate the correct and incorrect// usage of delete operator#include <cstdlib>#include <iostream>using namespace std; // Driver Codeint main(){ int x; int* ptr1 = &x; int* ptr2 = (int*)malloc(sizeof(int)); int* ptr3 = new int; int* ptr4 = NULL; // delete Should NOT be used like below because x is // allocated on stack frame delete ptr1; // delete Should NOT be used like below because x is // allocated using malloc() delete ptr2; // Correct uses of delete delete ptr3; delete ptr4; getchar(); return 0;} |
Example for free() function:
C++
// CPP program to demonstrate the correct and incorrect// usage of free() function#include <cstdlib>#include <iostream>using namespace std; // Driver Codeint main(){ int* ptr1 = NULL; int* ptr2; int x = 5; ptr2 = &x; int* ptr3 = (int*)malloc(5 * sizeof(int)); // Correct uses of free() free(ptr1); free(ptr3); // Incorrect use of free() free(ptr2); return 0;} |
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.







Please Login to comment...