deleting base pointer

pushpat's Avatar, Join Date: Feb 2012
Go4Expert Member
Hi Folks ,

I need your help, I am getting segmentation fault for "delete bptr_1" ( please refer program written below ).

If i remove statements "delete dptr;" inside try{}, then the program executes otherwise it will give error.

Could you please tell me why shouldnot i delete "dptr" inside try{}
Does delete dptr inside try{} deletes bptr_1 too?

Code:
#include<iostream>
using namespace 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;
}
Code:
OUTPUT:

(2) bptr_2 not pointing to derived
delete base ptr pointing to d
Segmentation fault
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
You get the segfault because you've already deleted the object pointed to by bptr_2 when you delete dptr. If you create an object pointed to by one pointer, then point another pointer at that same object (dptr = dynamic_cast<derived*>(bptr_1); ) then you still only have one object, and when you've deleted it (delete dptr; ) you can't delete it again (delete bptr_1; ).

This code
Code:
cout<<"delete base ptr pointing to d"<<endl;
suggests where your understanding could be at fault: delete PTR deletes the object pointed to by PTR. It does not delete the pointer itself.
pushpat like this
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Also
Code:
// assigning the pointer to null, to reuse
suggests some misunderstanding. You do not need to set a pointer to NULL to reuse it. This is C++, not Java, and there is no garbage collector. There's nothing at all wrong with:
Code:
int i, j; // create two ints

int *ptr; // define a pointer
ptr=&i; // we can now use ptr to manipulate i
// not setting ptr to NULL, and both i and j are still there
ptr=&j; // we can now use ptr to manipulate j
pushpat like this
0
pushpat's Avatar, Join Date: Feb 2012
Go4Expert Member
Thank you