×

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

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 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.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 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.

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.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.