0

I am currently making a code a class code for binary search tree but I am getting an error in the destructor for my BST class. This is my relevant part of code:

Node Struct:

struct Node{
    int key;
    struct Node* left;
    struct Node* right;
};

Function to Create new node:

Node* BST::CreateNode(int key){
    Node* temp_node = new Node();
    temp_node->key = key;
    temp_node->left = nullptr;
    temp_node->right = nullptr;
    return temp_node;
}

Assignment Operator:

BST& BST::operator=(const BST& cpy_bst){
    if (this != &cpy_bst){
        Node* cpy_root = cpy_bst.root;
        this->root=assgRec(cpy_root, this->root);
    }
    return *this;
}

 Node* BST::assgRec(Node* src_root, Node* dest_root){
    if (src_root != nullptr){
        dest_root = CreateNode(src_root->key);
        dest_root->left=assgRec(src_root->left, dest_root->left);
        dest_root->right=assgRec(src_root->right, dest_root->right);
    }
    return src_root;
}

Destructor:

BST::~BST(){

    DestroyNode(root);
}

 void BST::DestroyNode(Node* r){
        if (r != nullptr){
            DestroyNode(r->left);
            DestroyNode(r->right);
            delete r;
        }
    }

The problem is that after I have used the assignment in main function, like:

BST bin_tree2=bin_tree1;

The destructor is called but after it deletes the data in bin_tree1, all values that were placed in bin_tree2 have some junk values in them and I get an error on that part. Any help would be greatly appreciated. Thanks

Hamza750
  • 11
  • 4

1 Answers1

0

This looks like you are copying pointers and accessing them after memory has been deallocated.

The problem seems not to be with the keys as I said earlier but with the nodes that seem to be improperly constructed in the BST::assgRec function.

Lunar
  • 176
  • 8
  • It's exactly that problem but how exactly am I getting it? As far as I know, I'm only copying the value of src_root's key to dest_root's key. – Hamza750 Mar 26 '17 at 17:31