delete and free() in C++

Last Updated : 08 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 <iostream> using namespace std; class Test { int x; Test() { x = 5;} }; int main() { Test *t = new Test; cout << t->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<iostream> 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 <stdio.h> header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
Delete every Kth node from circular linked list
Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists. Examples: Input : n=4, k=2, list = 1->2->3->4 Output : 1->2->3->4->1 1->2->4->1 2->4->2 2->2 Input : n=9, k=4, list = 1->2->3->4->5->6->7->8->9 Output : 1->2->3->4
13 min read
How to delete last element from a map in C++
If we wish to delete the last element from a map, we can use following methods : using prev(mp.end()) : what prev function do is, it goes back one step back from the given iterator. So using prev function with mp.end() will return an iterator which points the last element of the map. Implementation: #include <bits/stdc++.h> using namespace st
2 min read
How to delete an element from the Set by passing its value in C++
Given a Set, the task is to remove the last element from this Set in C++.Examples: Input: set = [10 20 30 70 80 90 100 40 50 60], valueOfElementToBeDeleted = 100 Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5], valueOfElementToBeDeleted = 3 Output: 1 2 4 5 Sets are a type of associative container in which each element has to be unique b
6 min read
How to delete a range of values from the List using Iterator
Given a List, the task is to delete a range of values from this List using Iterator. Example: Input: list = [10 20 30 40 50 60 70 80 90], start_iterator = 3, end_iterator = 8 Output: 10 20 80 90 Input: list = [1 2 3 4 5] start_iterator = 1, end_iterator = 3 Output: 3 4 5 Approach: In this method, a range of elements are deleted from the list. This
2 min read
How to delete last element from a List in C++ STL
Given a List, the task is to remove the last element from this List in C++. Examples: Input: list = [10 20 30 70 80 90 100 40 50 60] Output: 10 20 30 40 50 60 70 80 90 Input: list = [1 2 3 4 5] Output: 1 2 3 4 Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value
3 min read
"delete this" in C++
Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. C/C++ Code class A { public: void fun() { del
1 min read
Delete elements in C++ STL list
How to insert elements in C++ STL List ? This article covers the deletion aspects in STL list. Using list::erase(): The purpose of this function is to remove the elements from list. Single or multiple contiguous elements in range can be removed using this function. This function takes 2 arguments, start iterator and end iterator. Time complexity :
4 min read
Delete multiple occurrences of key in Linked list using double pointer
Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2Output: 4 -> 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.This is mainly an alternative of this post which deletes multiple occurrence
6 min read
delete keyword in C++
delete is an operator that is used to destroy array and non-array(pointer) objects which are dynamically created by the new operator. delete can be used by either using the delete operator or delete [ ] operator.The new operator is used for dynamic memory allocation which stores variables on heap memory.This means the delete operator deallocates me
4 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
what happens when you don't free memory after using malloc()
Pre-requisite: Dynamic memory allocation in CThe "malloc" or "memory allocation" method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.Syntax: ptr = (cast-type*) malloc(byte-
3 min read
Count of square free divisors of a given number
Given an integer N, the task is to count the number of square-free divisors of the given number. A number is said to be square-free, if no prime factor divides it more than once, i.e., the largest power of a prime factor that divides N is one. Examples: Input: N = 72 Output: 3 Explanation: 2, 3, 6 are the three possible square free numbers that div
6 min read
free() Function in C Library With Examples
The free() function in C is used to free or deallocate the dynamically allocated memory and helps in reducing memory wastage. The C free() function cannot be used to free the statically allocated memory (e.g., local variables) or memory allocated on the stack. It can only be used to deallocate the heap memory previously allocated using malloc(), ca
3 min read
How does free() know the size of memory to be deallocated?
Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc(). void free(void *ptr); Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer? Following is the most common way to store size of memor
1 min read
How to deallocate memory without using free() in C?
Question: How to deallocate dynamically allocate memory without using “free()” function. Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of "realloc()" from "stdlib.h" C/C++ Code void *realloc(void *ptr, size_t size); If "size" is zero, then call to realloc is equiva
2 min read
Learn Free Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. Programming languages are an essential part of software development because they create a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, searc
9 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Article Tags :
Practice Tags :