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.