Delete keyword in C++

Delete Operator in C++

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

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

Delete: Delete keyword 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
Delete in C++

C++ program demonstrates the usage of delete keyboard

#include<iostream>
using namespace std;

main()
{

int *p ,i,n;
cout<<"enter the size:";
cin>>n;
int *p=new int[n];//allocates n*sizeof(int) bytes

if(p==NULL)//in rare case if available memory not available
{
cout<<"\nmemory alloacation failed";
exit(1);
}

cout<<"\nenter the elements\n";
for(int i=0;i<n;i++)
{
cin>>*(p+i);
}

cout<<"\nelements are:\n";
for(int i=0;i<n;i++)
{
cout<<"adress:"<<(p+i)<<"\tvalue:"<<*(p+i)<<"\n";
}
delete []p;//entire array memeory gets deleted
cout<<*(p+1);//you will get zero becasue data is deleted

}

Output

Enter the size 
5
Enter the elements

1 6 0 8 3

Elements are:
1 6 0 8 3

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

Please Login/Signup to comment