Deleting pointers in functions and also destructors

I'm having a problem when deleting a pointer in a destructor. The pointer is a member variable in a class. I initialize it in a member function and delete at the end of the same function. However, I also have included the delete pointer statement in the class destructor just in case. The problem is that if all goes well the pointer gets deleted in the function and then the destructor throws an exception because the pointer is invalid. How can I tell if the pointer is valid and that the memory is already free? Checking if the pointer is 0 doesn't seem to work. What am I missing?

Also, if I have another pointer defined locally in a function and I use new to initialize it, how can I call delete if an exception is thrown before the delete statement is encountered?
boomerang061797Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

boomerang061797Author Commented:
Edited text of question.
0
joshaubryCommented:
1. in the destructor delete myPointer as follows

try
{
   delete myPointer;
}
catch(...)
{
}

you also might try this statement

if(myPointer != NULL)
   delete myPointer;

2. if you want to delete your localPointer when the exception is thrown, do it in the catch statement

try
{
   //your exception throwing code here
}
catch(...)
{
   delete localPointer;
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jasonclarkeCommented:
you shouldn't need to catch an exception when deleting the pointer.  The most likely reason for an exception is deleting memory twice.

Make sure the pointer is always set to zero after it is deleted:

class X
{
   int*  mPtr;
public:
   X() : mPtr(0) {}
   void func() {
       mPtr = new int(7);
       //... Do something
       delete mPtr;
       mPtr = 0;  // This is the crtical bit
   }
   ~X() { delete mPtr; } // Should now be OK now
};
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

boomerang061797Author Commented:
What you say is correct, however the comment from Jasonclarke is what I was looking for.
0
nietodCommented:
>> What you say is correct
It really isn't!   Trust Jason on this one.  If you think joshaubry is right in any way, say so, because you don't understand.

I'm not sure when Janson answered, but usually you would award the points to the expert that contribitued the right answer, in this case jason.
0
boomerang061797Author Commented:
Well it looks correct, but I haven't tried it out for myself. Of course it is looks a little arkward to have a try-catch block in the destructor just to catch exceptions which you cause yourself.

The comment regarding the if (myPointer == NULL) doesn't quite work - this I tried (well really I tried mypointer == 0). The delete operator should set the pointer to 0 after freeing memory in my opinion.

What part is it that you mean is totally wrong? The part regarding deletion of the local pointer?

How do I go about giving points to jasonclarke when I see no options on this web page that allows me to do so (without disregarding joshaubry's answer?)
0
jasonclarkeCommented:
I think the point is that the stuff about try/catch around delete is misleading at best.

you are lucky that delete is throwing an exception at all (is your program compiled in debug mode? that maybe the reason for the exception).  Normally deleting a pointer twice will cause memory corruption, which will result in a crash at somepoint (maybe immediately but more difficult to spot at some random time in the future).

you should always set a pointer to zero after delete if you intend to use it again.
0
nietodCommented:
Right deleting a pointer twice, your actuall mistake, does not necessarily cause a C++ excepton, in fact it almost never would.  It may throw an OS exception, if the OS supports such a thing, but that would not usually be caught by a C++ catch.  In most cases, deleting the pointer twice just causes a total mess that is impossible to safely detect.  So the approach must be to avoid deleting the pointer the second time, not cleaning up after it takes place.  Okay?  

Also

if(myPointer != NULL)
   delete myPointer;

is silly for two reasons.  First you rproblem was that the pointer still contained its old (non-NULL) value, so that code would not protect against the 2nd delete anyways.  Second, it is harmless to delete a NULL pointer, so there is no need to test if the pointer is NULL before deleting.  (It is a waste of time, because delete is going to make that same check itself, don't bother checking twice.)
0
joshaubryCommented:
oops...looks like my answer was wrong...these guys have way more experience than i

if there's any way i can help get the points transferred to the deserving parties, let me know
0
nietodCommented:
Jason would be the one that deserves them.  One thing you could do is to ask a 100pt "question" for jason to answer.  But that will cost you 100 pts, which you might not have or might be low on.
0
joshaubryCommented:
i only got sixty right now, but i'll keep that in mind for two weeks from now or so...
0
cetinskiCommented:
I think the main problem here, (which nobody mentions), is that when you delete a pointer, depending on what compiler you have, the pointer does not necessarily get set back to NULL.
0
nietodCommented:
>> depending on what compiler you have,
>> the pointer does not necessarily get set back to NULL.
It doesn't depend on the compiler at all.  No compiler should ever set the pointer to NULL.

And it is not likely to be "a" problem much less the "main problem" as this occurs in a destructor.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.