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)

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.