Open In App

delete and free() in C++

Last Updated : 08 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
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



Similar Reads

new vs malloc() and free() vs delete in C++
We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++. The functionality of the new or malloc() and delete or free() seems to be the same but they differ in various ways.The behavior with respect to constructors and destructors calls differ in the
5 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
C++ | new and delete | Question 2
Which of the following is true about new when compared with malloc. 1) new is an operator, malloc is a function 2) new calls constructor, malloc doesn't 3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type. (A) 1 and 3 (B) 2 and 3 (C) 1 and 2 (D) All 1, 2 and 3 Answer: (D) Explanation: See mall
1 min read
C++ | new and delete | Question 3
Predict the output? #include &lt;iostream&gt; using namespace std; class Test { int x; Test() { x = 5;} }; int main() { Test *t = new Test; cout &lt;&lt; t-&gt;x; } (A) Compiler Error (B) 5 (C) Garbage Value (D) 0 Answer: (A) Explanation: There is compiler error: Test::Test() is private. new makes call to the constructor. In class Test, constructor
1 min read
C++ | new and delete | Question 4
What happens when delete is used for a NULL pointer? int *ptr = NULL; delete ptr; (A) Compiler Error (B) Run-time Crash (C) No Effect Answer: (C) Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.Quiz of this Question
1 min read
C++ | new and delete | Question 5
Is it fine to call delete twice for a pointer? #include&lt;iostream&gt; using namespace std; int main() { int *ptr = new int; delete ptr; delete ptr; return 0; } (A) Yes (B) No Answer: (B) Explanation: It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing. Quiz of this Question
1 min read
Different ways to delete elements in std::map (erase() and clear())
This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following ways: A. Remove using the Keyerase (key) Erases t
4 min read
Overloading New and Delete operator in c++
The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.If overloading is done out
5 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
C program to delete a file
The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the &lt;stdio.h&gt; header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
Article Tags :
Practice Tags :