×

Delete Operator in C++

Overview

We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must manually deallocate the dynamically allocated memory. Using the delete operators, we may dynamically deallocate memory.

Memory Management : An Overview

The new and delete operators in C++ provide dynamic memory (that is, the allocation of memory or at runtime by the programmer) and object allocation and deallocation.

When you no longer need to utilise a dynamically defined variable in C++, you can deallocate the memory used by the variable by using the "delete" operator.

You may use the delete operators to allocate memory to the array at runtime, which is one of the applications or uses of dynamic memory allocation in data structures.

Delete Operator in C++ :

Because the coder has allotted space at runtime, it is the programmer's responsibility to destroy that memory when it is no longer needed. When programmers decide that a dynamically created variable is no longer needed, they can use the "delete" operator to free up the memory it takes in the free store or heap. The memory is returned to the operating system. Memory deallocation is another name for this. Additionally, after the programme is finished, memory will be automatically deallocated.

Syntax :

For deallocating memory for only one element.

delete pointer_var;

For deallocating memory for an array.

delete [] pointer_var;

In the aforementioned syntaxes, memory that was pointed by pointer_var has been removed.

For example :

delete scalar

The memory indicated by the variable 'scalar' will be deallocated in the provided example.

It's beneficial to employ dynamic memory allocation for flexibility and other purposes, however if the programmer fails to deallocate memory, a memory leak might occur (in which memory is not deallocated until the programme terminates). For good coding practise and to minimise memory leaks, programmers should explicitly erase the dynamically allocated memory.

Why is delete operator required ?

We all know that when a programme exits or shuts down, variables are automatically deallocated/deleted, but it's important to use the delete operator in order to reuse the memory allocated in the programme if necessary and avoid situations like memory not being left or allocation of a space having an unknown value.

Using the delete() method to delete an array object :

In C++, the delele [] operator may be used to efficiently delete array objects. We'll show you how to remove arrays in C++ in the code below.

Example :

#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Allocating the Heap memory 
    int* arr = new int[7];  
      
    // Deallocating the Heap memory 
    delete[] arr;  
    cout << "Array Deleted." << endl;
    return 0; 
}

Output :

Array Deleted.

Explanation :

In the above example, we created a new array called arr first, using new keyword to allocate the heap memory. Then we used the delete[] method to deallocate the heap memory and erase the data. Thus, we got our required output.

Using the delete() method to delete NULL pointers :

The pointer to the object or variable is not removed during the delete operation on pointers. As a result, the delete operation clears the RAM memory region to which the pointer corresponds.

Example :

#include <bits/stdc++.h> 
using namespace std; 
  	
int main() 
{ 
    // pntr is the given NULL pointer 
    int* pntr = NULL; 
  
    // deleting the pntr 
    delete pntr; 
    
    cout<<"NULL pointer Deleted"<<endl;
    return 0; 
}

Output :

NULL pointer Deleted

Explanation :

In the above example, a NULL pointer was given as a Pointer which was allocated in the memory. Using the delete method we deallocated that NULL pointer from the memory successfully. Thus, the memory held by the NULL pointer variable has been deleted.

Using the delete operator to delete a void pointer :

The delete operator may be used to efficiently clear up memory space taken up by the void pointer variable.

Example :

#include <bits/stdc++.h> 
using namespace std; 
 
int main() 
{ 
    void* strng;   
    
    delete strng;
  
    cout<<"Void Pointer Deleted"<<endl;
    return 0; 
}

Output :

Void Pointer Deleted

Explanation :

In the above example, a void pointer named strng was allocated to the memory. Then we used the delete operator to deallocate the void pointer strng from the memory.

Using the delete() method to erase dynamically allocated memory :

The delete operator can be used to erase memory that has been dynamically allocated to the pointer variable using the malloc() method.

Example :

#include <bits/stdc++.h> 
using namespace std; 
 
int main() 
{ 
    char* strng = (char*)malloc(sizeof(char));
     
    delete strng; 
    
    cout<<"Pointer memory allocated dynamically is Deleted"<<endl;
    return 0; 
}

Output :

Pointer memory allocated dynamically is Deleted

Explanation :

In the above example, the pointer variable strng was allocated memory dynamically. Then the delete operator was used to erase memory that has been dynamically allocated to the pointer variable using the malloc() method.


Related Topics

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.