Detecting null dereferences in member functions.

August 27th 2004 04:43 am

Today’s C++ example involves detecting the use of null pointer dereferences from within your member functions. It’s not common since there’s really not much you can do when you detect this situation, but I find it’s somewhat neat anyways.

The idea is that in a member function, you can examine the value of this, to see if it’s null. If so, you can print out a whine message or something like that.

#include 

using namespace std;

class Test
{
    public:
    void tryToDie() const;
};

void Test::tryToDie() const
{
    if (this == 0) {
        cout tryToDie();

    test = new Test;

    cout tryToDie();

    delete test;

    return 0;
}

If you run that program, you should get output somewhat like the following.

Testing null pointer.
HA!  You tried to dereference a null pointer you silly silly person.
Testing valid pointer.

Posted by mpyne under Uncategorized |

Trackback URI | Comments RSS

Leave a Reply


For spam filtering purposes, please copy the number 2119 to the field below This message appears because you have JavaScript disabled or your browser does not support CSS, a standard web feature.