Users Online
· Guests Online: 40
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Newest Threads
No Threads created
Hottest Threads
No Threads created
Latest Articles
Articles Hierarchy
New and Delete Operators in C++
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.
-
/*
-
* 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)
Comments
No Comments have been Posted.
Post Comment
Please Login to Post a Comment.