Nov 12, 2016 at 12:37am UTC
Hello guys,
after copy constructor is done, console crashes... Any idea?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
template <class bstitem>
class BinarySearchTree
{
private :
struct Node
{
bstitem data;
Node* left;
Node* right;
Node(bstitem newdata): data(newdata), left(NULL), right(NULL) {}
};
typedef struct Node* NodePtr;
NodePtr root;
void copyConHelper(NodePtr root, NodePtr origin);
public :
BinarySearchTree();
//Instantiates a new Binary Search Tree
//post: a new Binary Search Tree object
~BinarySearchTree();
//destructor
BinarySearchTree(const BinarySearchTree &BinarySearchTree);
};
template <class bstitem>
BinarySearchTree<bstitem>::BinarySearchTree(const BinarySearchTree &BST):root(BST.root)
{
if (BST.root == NULL)
{
root = NULL;
}
else
{
copyConHelper(root, BST.root);
}
}
template <class bstitem>
void BinarySearchTree<bstitem>::copyConHelper(NodePtr root, NodePtr origin)
{
if (origin == NULL)
{
root = NULL;
}
else
{
root = new Node(origin->data);
copyConHelper(root->left, origin->left);
copyConHelper(root->right, origin->right);
}
}
Last edited on Nov 12, 2016 at 12:37am UTC
Nov 12, 2016 at 1:50am UTC
I would imagine it's more likely when the destructor is called since your code only makes a shallow copy of the tree, so assuming you delete things in your destructor, the same pointer value would be fed to delete more than once (resulting in undefined behavior.)
Your copyConHelper does nothing. The only variables it modifies are local to the function itself.