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.
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]Related Posts:
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check Programming Books
- Check Computer Science Books
- Check C++ Books