Users Online

· Guests Online: 40

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

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.

  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)

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.86 seconds
10,818,160 unique visits