Dangling Pointer:
#include<iostream>
using namespace std;
void main()
{
int * ptr1 = new int(1000);
int * ptr2 = ptr1;
cout<<"ptr1 = "<<ptr1<<endl;
cout<<"ptr2 = "<<ptr2<<endl<<endl;
cout<<"*ptr1 = "<<*ptr1<<endl;
cout<<"*ptr2 = "<<*ptr2<<endl<<endl;
delete ptr1;
cout<<"ptr2 = "<<ptr2<<endl<<endl;
cout<<"*ptr2 = "<<*ptr2<<endl<<endl;
//print garbage since the heap variable with 1000 has be released
}
Lost Heap Variables:
#include<iostream>
using namespace std;
void main()
{
int * ptr1 = new int(1000);
cout<<"ptr1 = "<<ptr1<<endl;
cout<<"*ptr1 = "<<*ptr1<<endl<<endl;
ptr1 = new int(500);
//The heap
variable with 1000 is lost for reference. No one can refer to it.
cout<<"ptr1 = "<<ptr1<<endl;
cout<<"*ptr1 = "<<*ptr1<<endl;
delete ptr1;
}