Cpp - Pointer delete Keyword

Introduction

Calling delete on the pointer returns the memory to the heap.

The memory allocated with the new operator is not freed automatically.

To restore the memory to the heap, you use the keyword delete. For example:

delete pPointer; 

When you delete the pointer, you are freeing up the memory whose address is stored in the pointer.

The pointer can be reassigned after the delete operation.

The following code shows how to use new and delete operators.

Demo

#include <iostream> 
 
int main() /*from  w ww .j av  a 2s .  co m*/
{ 
    int localVariable = 5; 
    int *pLocal= &localVariable; 
    int *pHeap = new int; 
    if (pHeap == nullptr) 
    { 
           std::cout << "Error! No memory for pHeap!!"; 
           return 1; 
    } 
    *pHeap = 7; 
    std::cout << "localVariable: " << localVariable << "\n"; 
    std::cout << "*pLocal: " << *pLocal << "\n"; 
    std::cout << "*pHeap: " << *pHeap << "\n"; 
    delete pHeap; 
    pHeap = new int; 
    if (pHeap == nullptr) 
    { 
           std::cout << "Error! No memory for pHeap!!"; 
           return 1; 
    } 
    *pHeap = 9; 
    std::cout << "*pHeap: " << *pHeap << "\n"; 
    delete pHeap; 
    return 0; 
}

Result

Exercise