New and Delete Operators in C++
Posted by Superadmin on August 10 2022 08:20:15

New and Delete Operators in C++

 

 

This C++ Program which demonstrate using keywords new and delete. The program dynamically allocates a pointer to int using keyword ‘new’, deletes it using keyword ‘delete’ and is set to NULL. We are required to set the pointer to NULL since it prevents further use of the pointer.

 

Here is source code of the C++ program which demonstrate using keywords new and delete. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate using keywords new and delete
  3.  */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int num;
  11.     cout << "Enter the number    : ";
  12.     cin >> num;
  13.  
  14.     /* Dynamically allocating value using new */
  15.     int * val = new int(num);
  16.     cout << "Value of variable : " << *val << endl;
  17.     /* Deleting allocated storage using delete */
  18.     delete val;
  19.     /* Setting 'val' to NULL is advised to avoid complications */
  20.     val = NULL;
  21.     /* Using deleted pointer causes segmentation fault */
  22.     cout << "Value of variable : " << *val << endl;
  23. }

 

$ g++ main.cpp
$ ./a.out
Enter the number    : 15
Value of variable   : 15
Segmentation fault (core dumped)