C++ Programs Delete Operator
In C++, delete
operator is used for dynamic memory allocation. It deallocates the memory allocated by the new
operator. It frees the memory block pointed to by the given pointer.
Syntax
delete pointer;
Here, pointer
is a pointer to a block of memory that was previously allocated using the new
operator.
Example
#include<iostream>
using namespace std;
int main()
{
int *ptr = new int;
*ptr = 10;
cout << "Value of ptr: " << *ptr << endl;
delete ptr;
return 0;
}
Output
Value of ptr: 10
Explanation
In the above example, we have allocated a memory block of type int
using the new
operator and assigned a value of 10 to it. Then, we have used the delete
operator to deallocate the memory block.
Use
The delete
operator is used to free the memory allocated using the new
operator. It should always be used to avoid memory leaks.
int main()
{
int *ptr = new int;
*ptr = 10;
// some code
delete ptr;
return 0;
}
In the above example, the memory allocated to ptr
is freed using the delete
operator before the program terminates.
Important Points
- The
delete
operator deallocates the memory allocated by thenew
operator. - It is used to free the memory block pointed to by the given pointer.
- The
delete
operator should always be used to avoid memory leaks.
Summary
In summary, the delete
operator in C++ is used to deallocate memory allocated dynamically using the new
operator. It frees the memory block pointed to by the given pointer. It is important to always use the delete
operator to avoid memory leaks.