Search code examples
c++binary-treebinary-search-tree

C++: Program for Deleting a node and return its right child:


I was attempting to solve the question for deleting a node in BST, and saw a strange output. In the case where node has only right child, I was trying to delete that node and return its right child. Somehow, both of the codes below gave the correct result, even though it seems to me like only code 1 should work since we're trying to access a deleted node. Can someone tell me why this happens?

cpp Code 1:

Node* temp = root->right;
delete root;
return temp;

Code 2:

Node* temp = root;
delete temp;
return root->right;

Solution

  • The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work.

    There is no promise that an exception will be thrown, or that an error message will be displayed.

    The specific language in the C++23 Standard appears in Section 6.7.5.1 [basic.stc.general], where item 4 states, "Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior."