New and Delete Operators in C++

bookmark

#include<iostream>
using namespace std;
 
int main()
{
    int num;
    cout << "Enter the number    : ";
    cin >> num;
 
    /* Dynamically allocating value using new */
    int * val = new int(num);
    cout << "Value of variable : " << *val << endl;
    /* Deleting allocated storage using delete */
    delete val;
    /* Setting 'val' to NULL is advised to avoid complications */
    val = NULL;
    /* Using deleted pointer causes segmentation fault */
    cout << "Value of variable : " << *val << endl;
}

 

Output:
Enter the number    : 15
Value of variable   : 15
Segmentation fault (core dumped)