Horje
How to Delete a Pointer in C++?

In C++, memory management is essential to avoid memory leaks, crashes, and undefinable behavior. In this article, we will learn how to properly delete a pointer in C++.

Deleting a Pointer in C++

By deleting a pointer, we refer to deleting the memory allocated to the pointer. To delete a pointer in C++ we can use the delete keyword and for arrays allocated with new, use delete[] to deallocate the memory.

After, deleting or deallocating the memory, we should assign the nullptr to the pointer.

Syntax to Delete the Pointer in C++

For deleting the pointer variable use:

delete pointerName;

For deleting the pointer array use:

delete[] arrayPointer;

Also, if you have used the malloc() or calloc() function to allocate the memory, then use the free() function for deallocation.

C++ Program to Delete a Pointer

The below example demonstrates how we can delete a pointer properly in C++.

C++

// C++ program to show how to delete a pointer properly
#include <iostream>
using namespace std;
  
int main()
{
    // Allocate memory for a single integer
    int* dynamicInt = new int;
  
    // Check if the pointer is not null before deleting
    if (dynamicInt != nullptr) {
  
        // Use the allocated memory
        *dynamicInt = 42;
  
        // Display the value
        cout << "Value of dynamicInt: " << *dynamicInt
             << endl;
  
        // Properly delete the pointer
        delete dynamicInt;
        dynamicInt = nullptr;
        // Set to null after deletion to avoid dangling
        // pointer
    }
  
    return 0;
}

Output

Value of dynamicInt: 42

Note: Undefined behavior occurs when attempting to remove a single point more than one time. So, before deleting the pointer, always check that it is not null .




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Use Default Arguments in Function Overloading in C++? How to Use Default Arguments in Function Overloading in C++?
How to Use the Volatile Keyword in C++? How to Use the Volatile Keyword in C++?
How to Read a Paragraph of Text with Spaces in C++? How to Read a Paragraph of Text with Spaces in C++?
How to Find the Mode in a Sorted Array in C++? How to Find the Mode in a Sorted Array in C++?
How to Implement Priority Queue Using Multimap in C++? How to Implement Priority Queue Using Multimap in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12