Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
delete keyword in C++
Next article icon

delete keyword in C++

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

delete is an operator that is used to destroy array and non-array(pointer) objects which are dynamically created by the new operator.

  • delete can be used by either using the delete operator or delete [ ] operator.
  • The new operator is used for dynamic memory allocation which stores variables on heap memory.
  • This means the delete operator deallocates memory from the heap.
  • The pointer to the object is not destroyed, the value or memory block pointed by the pointer is destroyed.
  • The delete operator has void return type which means it does not return any value.

Below are some examples of where we can apply the delete operator:

1. Deleting Array Objects

We delete an array using [] brackets.

C++
// Program to illustrate deletion of array  #include <bits/stdc++.h> using namespace std;  int main() {     // Allocate Heap memory     int* array = new int[10];      // Deallocate Heap memory     delete[] array;      return 0; } 

2. Deleting NULL Pointer

Deleting a NULL does not cause any change and gives no error.

C++
// C++ program for deleting // NULLL pointer  #include <bits/stdc++.h> using namespace std;  int main() {     // ptr is NULL pointer     int* ptr = NULL;      // deleting ptr     delete ptr;      return 0; } 

3. Deleting Pointer With or Without Value

The memory pointed out by the specified pointer will be deallocated from the heap memory.

C++
// C++ program for deleting pointer with or without value  #include <bits/stdc++.h> using namespace std;  int main() {     // Creating int pointer     int* ptr1 = new int;      // Initializing pointer with value 20     int* ptr2 = new int(20);      cout << "Value of ptr1 = " << *ptr1 << "\n";     cout << "Value of ptr2 = " << *ptr2 << "\n";      // Destroying ptr1     delete ptr1;     // Destroying ptr2     delete ptr2;      return 0; } 

Output
Value of ptr1 = 0 Value of ptr2 = 20

4. Deleting a Void Pointer

The delete operator does not only deallocate the memory, but it also calls the destructor of the object to be deleted. That is why, if we use void pointer with delete, it will lead to undefined behaviour.

C++
// C++ prgram for deleting a void pointer  #include <bits/stdc++.h> using namespace std; int main() {     // Creating void pointer     void* ptr;     // Destroying void pointer     delete ptr;      cout << "ptr deleted successfully";     return 0; } 

Output
ptr deleted successfully

5. Deleting Memory Dynamically Allocated by malloc()

Deallocating memory allocated by malloc() using the delete operator also leads to undefined behavior. It is recommended to use delete for new and free() for malloc. 

C++
// C++ program for deleting memory dynamically allocated by // malloc   #include <bits/stdc++.h> using namespace std;  int main() {     // Dynamic memory allocated by using malloc     int* ptr2 = (int*)malloc(sizeof(int));      delete ptr2;      cout << "ptr2 deleted successfully";      return 0; } 

Output
ptr2 deleted successfully

Note: Although the above program runs fine on GCC. It is not recommended to use delete with malloc().

6. Deleting Variables of User-Defined Data Types

C++
// C++ program for deleting variables of User Defined data // types  #include <bits/stdc++.h> using namespace std;  struct P {     // Overloading delete operator for single object     // deallocation     static void operator delete(void* ptr, size_t sz)     {         cout << "custom delete for size " << sz << endl;         // ::operator delete(ptr) can also be used         ::operator delete(ptr);     }      // Overloading delete operator for array deallocation     static void operator delete[](void* ptr, size_t sz)     {         cout << "custom delete for size " << sz << endl;         // ::operator delete(ptr) can also be used         ::operator delete(ptr);     } };  int main() {     P* var1 = new P;     delete var1;      P* var2 = new P[10];     delete[] var2; } 

Output
custom delete for size 1 custom delete for size 18

Exceptions

1. Trying to Delete a Non-Pointer Object

C++
// C++ program for trying to delete a Non-pointer object  #include <bits/stdc++.h> using namespace std;  int main() {     int x;      // Delete operator always     // requires pointer as input     delete x;      return 0; } 


Output

error: type ‘int’ argument given to ‘delete’, expected pointer

2. Trying to Delete the Pointer to a Local Stack-Allocated Variable

C++
// C++ program for trying to delete the pointer to a local // stack-allocated variable  #include <bits/stdc++.h> using namespace std;  int main() {     int x;     int* ptr1 = &x;      // x is present on stack frame as     // local variable, only dynamically     // allocated variables can be destroyed     // using delete operator     delete ptr1;      return 0; } 


Output

main.cpp: In function ‘int main()’:
main.cpp:16:12: warning: ‘void operator delete(void*, std::size_t)’ called on unallocated object ‘x’ [-Wfree-nonheap-object]
16 | delete ptr1;
| ^~~~
main.cpp:9:9: note: declared here
9 | int x;
| ^
free(): invalid pointer

Related Articles

  • new keyword
  • C++ malloc()

Next Article
delete keyword in C++

A

Abhishek rajput
Improve
Article Tags :
  • C++
  • cpp-operator
  • Dynamic Memory Allocation
  • C++-new and delete
  • cpp-memory-management
Practice Tags :
  • CPP
  • cpp-operator

Similar Reads

    "delete this" in C++
    Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefi
    1 min read
    C++ Keywords
    Keywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
    2 min read
    Using Keyword in C++ STL
    The using keyword in C++ is a tool that allows developers to specify the use of a particular namespace. This is especially useful when working with large codebases or libraries where there may be many different namespaces in use. The using keyword can be used to specify the use of a single namespace
    6 min read
    Overloading New and Delete operator in c++
    The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes.  If these operators are overloaded using member function for a class, it means that these operators are overloaded only
    5 min read
    delete and free() in C++
    delete and free() in C++ have similar functionalities but they are different. In C++, the delete operator should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer, and free() should only be used for deallocating the memory allocated either using m
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences