











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.


Already learned about the new keyword in detail now will see how delete keyboard 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 keyboard
#include<iostream> using namespace std; int 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 return 0; }
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 requestDifference 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
Login/Signup to comment