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.
/*
* C++ Program to Demonstrate using keywords new and delete
*/
#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;
}
$ 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.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Programming MCQs
- Apply for Information Technology Internship
- Practice Computer Science MCQs
- Apply for C++ Internship
- Buy Computer Science Books