Open In App

delete and free() in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

delete and free() in C++ have similar functionalities but they are different. In C++, the delete operator should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer, and free() should only be used for deallocating the memory allocated either using malloc(), calloc(), realloc() or for a NULL pointer.

Difference between delete and free()

delete

free()

It is an operator.

It is a library function.

It de-allocates the memory dynamically.

It destroys the memory at runtime.

It should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer.

It should only be used for deallocating the memory allocated either using malloc(), calloc(), realloc() or for a NULL pointer.

This operator calls the destructor before it destroys the allocated memory.

This function only frees the memory from the heap. It does not call the destructor.

It is comparatively solwer because it invokes the destructor for the object being deleted before deallocating the memory.

It is faster than delete operator.

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 calls the destructor to ensure cleanup and resource deallocation for objects.

Example 1

The below program demonstrates the usage of the delete operator.

C++




// CPP program to demonstrate the correct and incorrect
// usage of delete operator
#include <cstdlib>
#include <iostream>
using namespace std;
 
// Driver Code
int 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 2

The below program demonstrates the usage of free() function.

C++




// CPP program to demonstrate the correct and incorrect
// usage of free() function
#include <cstdlib>
#include <iostream>
using namespace std;
 
// Driver Code
int 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;
}


Related Articles



Last Updated : 08 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads