Using new Keyword to allocate memory, delete to return the memory to the heap. - C++ Operator

C++ examples for Operator:new

Description

Using new Keyword to allocate memory, delete to return the memory to the heap.

Demo Code

#include <iostream> 
 
int main() /*  ww w  .j a v  a2  s . c  o  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


Related Tutorials