Search code examples
c++c++11nullptr

Does setting a pointer to nullptr affect other pointers pointing to the same address?


Consider the following function which erases a node from a binary search tree if the node has no children:

void erase_no_children(node* todel)
{
    //...
    if (todel->parent->left == todel) //if todel is left child
        todel->parent->left = nullptr;

    if (todel->parent->right == todel) //if todel is right child
        todel->parent->right = nullptr;

    delete todel;
}

Since todel->parent->left == todel that means that by setting todel->parent->left to nullptr, I'm just as well setting todel to nullptr. The compiler doesn't complain at all.

Question: Is this safe to do? Does it leak? Or is it undefined behaviour?


Solution

  • Since todel->parent->left == todel that means that by setting todel->parent->left to nullptr, I'm just as well setting todel to nullptr.

    That's not correct. todel and todel->parent->left are distinct pointer variables; setting one to nullptr doesn't affect the other.

    So you're not deleting nullptr (which would be safe and a no-op).