Maanu
Maanu

Reputation: 5203

NULL Pointer Call Fail Immediately

I have a NULL pointer named pTest. Is it possible to make the application crash immediately, if a function is invoked using the pointer.

Upvotes: 0

Views: 192

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308412

Instead of using a raw pointer, you can create a protected pointer class (a form of smart pointer) that traps dereferences.

#include <stdexcept>

template<typename T>
class CheckedPointer
{
    T * ptr;
public:
    CheckedPointer(T * init = NULL) : ptr(init) {}
    T * operator->() const
    {
        if (ptr == NULL)
            throw std::runtime_error("dereference of NULL pointer");
        return ptr;
    }
    T & operator*() const
    {
        if (ptr == NULL)
            throw std::runtime_error("dereference of NULL pointer");
        return *ptr;
    }
    // ... more members to make this a useful class
};

class Test
{
public:
    void Foo() {}
};

int main()
{
    CheckedPointer<Test> pTest;
    pTest->Foo();
}

http://ideone.com/R4mUK

Upvotes: 4

asdfjklqwer
asdfjklqwer

Reputation: 3594

Your question needs clarification. If pTest is a null pointer to an object and you invoke a method on it, then I'd expect your VS2008 compiled program to crash on its own if either:

  1. The method is virtual
  2. The method tries to access an instance member

This implies that the method call may actually work if it's semantically static and doesn't try to access instance members. Furthermore, the behaviour of this sort of thing varies between debug and release builds.

But if you are wanting to make your app crash directly before/when a method invocation is attempted, then you can add assertions or conditional aborts before each one. Or you could add a (this == NULL) check at the beginning of each method (but this won't work on virtual methods which will trigger a crash before reaching this point).

Upvotes: 1

MPelletier
MPelletier

Reputation: 16697

You might want to throw an Exception and just never catch it. That will crash your program.

if (pTest == NULL)
  throw std::invalid_argument("null pointer");

Upvotes: 0

Related Questions