-1

I have the following code:

typedef struct TreeNode
{
    int data;
    TreeNode *lchild, *rchild;
} TreeNode;
TreeNode *CreateBTNode(TreeNode *bt) // pre-build
{
    char ch;
    cin >> ch;
    if (ch == '#')
        bt = nullptr;
    else
    {
        bt = (TreeNode *)malloc(sizeof(TreeNode));
        bt->data = ch;
        bt->lchild = CreateBTNode(bt->lchild);
        bt->rchild = CreateBTNode(bt->rchild);
    }
    return bt;
}
void DeleteBiTree(TreeNode *&bt) 
{
    if (!bt)
        return;
    DeleteBiTree(bt->lchild);
    DeleteBiTree(bt->rchild);
    free(bt);
    bt = nullptr;
}
void PreOrder(TreeNode *bt)
{
    if (bt)
    {
        cout << bt->data << " ";
        PreOrder(bt->lchild);
        PreOrder(bt->rchild);
    }
}
int main()
{
    TreeNode *tree = CreateBTNode();
    TreeNode *tmp = tree;

    DeleteBiTree(tree);       // line 1

    DeleteBiTree(tmp);        // line 2

    PreOrder(tree);           // line 3
    
    return 0;
}
    

In this code the tree and tmp have the same address. when i delete this tree using line 1 and output the tree, there is no output and it's right, but when i try to delete the tree using line 2, there comes to a mess, why? Thanks a lot.

9
  • 2
    Why TreeNode *&bt and not TreeNode *bt? Commented Sep 18, 2024 at 8:42
  • 1
    DeleteBiTree takes a reference to the pointer argument and modifies it. If you pass different pointers into the function, you'll modify different pointers. Commented Sep 18, 2024 at 8:44
  • 1
    Same situation: void f(int& a) { a = 1; } int main() { int x = 0; int y = x; f(y); cout << x; } prints '0', not '1'. Commented Sep 18, 2024 at 8:47
  • 4
    This is C with cout, not C++. Please don't write code like this and don't learn this. Don't use malloc in C++. Commented Sep 18, 2024 at 8:52
  • 2
    As a side note, a C++ compiler should not compile this code because you call CreateBTNode() without a parameter (which you do not need, anyway). Commented Sep 18, 2024 at 8:53

1 Answer 1

0

You have two TreeNode * objects pointing to one TreeNode object. When you call DeleteBiTree(tmp);, you destroy the TreeNode, then set one of those pointers to null. The other pointer now has an invalid value. Once a pointer has an invalid value, the only valid operation on it is assigning it a new value. Even comparing it to nullptr has undefined behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.