Search code examples
c++pointersnullptr

Validating a pointer to a pointer in C++


I am trying to write a function that receives a pointer, uses it, and then makes it point to a new object. In order to do this, I am using a ptr-to-ptr. This is how I validate the ptr-to-ptr received by my function:

void modifyPtr(Obj ** ptrToPtr)
{
    if (*ptrToPtr == nullptr)
    {
        return;
    }
    else
    {
        // Do everything else!
    }
}

While writing this, I thought: what if a client passes the following to my function?

Obj ** ptrToPtr = nullptr;
modifyPtr(ptrToPtr);

In that case, my validation will be dangerous, because I will be dereferencing a nullptr. So, should I add an additional step of validation?

void modifyPtr(Obj ** ptrToPtr)
{
    if (ptrToPtr == nullptr)
    {
        return;
    }
    else if (*ptrToPtr == nullptr)
    {
        return;
    }
    else
    {
        // Do everything else!
    }
}

I have never seen validation like this one before, which is why I am hesitant.

Please be aware that I know one should avoid using raw pointers in C++. I am working with old code, and I find this problem interesting.


Solution

  • Your first validation is wrong, because you dereference ptrToPtr before checking if it is null.

    You probably don't need to check the dereferenced pointer for null since you are going to change it anyway (unless you need to do something with the old object).

    However, you should prefer using references instead of double-pointers, eg:

    void modifyPtr(Obj* &Ptr)
    

    Then the caller can't pass in a null reference (without doing ugly hacks).