#include<iostream>
usingnamespace std;
class base
{
public:
virtual ~base()
{ }
};
class derived: public base
{
public:
~derived()
{ }
};
int main()
{
base *bptr_1 = new derived();
base *bptr_2 = new base();
derived *dptr;
try
{
dptr = dynamic_cast<derived*>(bptr_1);
if(dptr == 0)
cout<<"(1) base ptr1 not pointing to derived"<<endl;
delete dptr; // deleting memory allocated. If i remove this line,then program works
dptr = 0; // assigning the pointer to null, to reuse
dptr = dynamic_cast<derived*>(bptr_2);
if(dptr == 0)
cout<<"(2) bptr_2 not pointing to derived"<<endl;
}
catch (exception& err)
{
cout<<"error catched :"<<err.what()<<endl;
}
cout<<"delete base ptr pointing to d"<<endl;
delete bptr_1; //SEGFAULT HERE
cout<<"delete base ptr pointing to base"<<endl;
delete bptr_2;
cout<<"delete derived ptr"<<endl;
delete dptr;
return 0;
}
it looks like you are trying to delete a pointer cast twice. I may be wrong but casting a pointer is not the same as allocating new memory using "new".
int main()
{
base *bptr_1 = new derived(); //bptr_1 points to some memory on heap
base *bptr_2 = new base(); //bptr_2 points to some memory on heap
derived *dptr;
try
{
dptr = dynamic_cast<derived*>(bptr_1); //dptr now points to the same memory pointed to by bptr_1
if(dptr == 0)
//...
delete dptr; //Delete the memory pointed to by dptr, bptr_1 is now dangling
dptr = 0; //Notice, this should have also been done for bptr_1
dptr = dynamic_cast<derived*>(bptr_2); //dynamic_cast fails so dptr is null
if(dptr == 0)
cout<<"(2) bptr_2 not pointing to derived"<<endl;
}
catch (exception& err)
{
cout<<"error catched :"<<err.what()<<endl;
}
cout<<"delete base ptr pointing to d"<<endl;
delete bptr_1; //SEGFAULT HERE, because bptr_1 is dangling, if you would have set bptr_1 to null like dptr this would be ok
cout<<"delete base ptr pointing to base"<<endl;
delete bptr_2; //This is ok, currently because bptr_2 points to a valid memory block
cout<<"delete derived ptr"<<endl;
delete dptr; //Currently ok because dptr is null
return 0;
}
Deleting a null pointer has no effect if using the operator supplied by the standard library.