Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an established pointer value for a released pointee?

Some programmers like to set a pointer variable to null after releasing the pointee:

delete ptr;
ptr = 0;

If someone tries to release the pointee again, nothing will happen. In my opinion, this is wrong. Accessing a pointer after the pointee has been released is a bug, and bugs should jump in your face ASAP.

Is there an alternative value I could assign to a pointer variable that designates released pointees?

delete ptr;
ptr = SOME_MAGIC_VALUE;

Ideally, I would want Visual Studio 2008 to tell me "The program has been terminated because you tried to access an already released pointee here!" in debug mode.


Okay, it seems I have to do the checking myself. Anything wrong with the following template?

template <typename T>
void sole_delete(T*& p)
{
    if (p)
    {
        delete p;
        p = 0;
    }
    else
    {
        std::cerr << "pointee has already been released!\n";
        abort();
    }
}
like image 415
fredoverflow Avatar asked Jan 20 '11 11:01

fredoverflow


2 Answers

No. Test for "0" when trying to delete something if you really want to warn or error out about it.

Alternatively, during development you could omit ptr = 0; and rely on valgrind to tell you where and when you're attempting a double free. Just be sure to put the ptr = 0; back for release.

Edit Yes, people I know C++ doesn't require a test around delete 0;

I am not suggesting if (ptr != 0) delete ptr;. I am suggesting if (ptr == 0) { some user error that the OP asked for } delete ptr;

like image 155
Lightness Races in Orbit Avatar answered Sep 28 '22 07:09

Lightness Races in Orbit


Assign NULL after releasing a pointer. And before using it, check for its NULLity.. If it is null, report an error by yourself.

like image 33
liaK Avatar answered Sep 28 '22 06:09

liaK