Delete keyword in C++

Delete Operator in C++

Delete keyword in C++ is very helpful while dynamically allocate memory. Dynamic memory allocation enables a programmer to create and delete memory as per the requirement at any point of time other result memory wastage can be reduced. The 2 keywords new and delete are used for allocation and deallocation of memory respectively.
Delete keyword in C++

Delete keyword in C++

Already learned about the new keyword in detail now will see how delete keyword  works

Delete: Delete keyword in C++ is used to erase the memory allocated dynamically memory that is created using the new keyword and give back to the heap free store

  • Memory allocated dynamically using a new keyword is not deleted automatically user explicitly needs to delete it using the delete operator
  • Delete Keyword cannot delete memories that are created statically(compiler allocated memory in the stack)

Syntax:

delete ;

Example

delete p; //delete individual object

delete []p;// delete entire array

C++ program demonstrates the usage of delete keyword

Run
#include <iostream> 
using namespace std;

int main() {
    // Allocate memory for an array of integers
    int* arr = new int[5]; // Assign values to the array
    
    for(int i = 0; i < 5; i++) {
        arr[i] = i;
    } 
    // Print the values of the array
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;    // Deallocate the memory
    
    delete[] arr;
    
    for(int i=0; i<5; i++){
    cout << arr[i] << " ";
    }
    return 0;
}

Output

0 1 2 3 4 
1533846632 5 -1838056283 -1071475926 4

How delete works?

The new operator takes memory from freestore and allocates in the program whenever we delete the memory using  delete keyword it will return the memory of the object allocated to the free store so that the free store can  use it for another new allocation request

Difference between malloc()/free() and new/delete 

  • both malloc()/free and new/delete is used for dynamic memory management
  • The new and delete operators are having simple Syntax compare with these functions, and functions require  to perform explicit Type casting whereas new/delete  implicitly typecast based upon the data

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription