C++ Segfault on clearing a binary search tree
I'm trying to eliminate any memory leaks in in my Binary Search tree that I'm making so I made a simple recursive delete method. This is the method that first causes
void BST::copy(const BST& other){
if (other.root != NULL){
Clear();
Which Clear();
will first thing call recursiveDelete(root);
void BST::recursiveDelete(BSTNode * head){
if (head == NULL)
return;
recursiveDelete(head->left);
recursiveDelete(head->right);
delete head;
}
This code will Segfault and I don't know why. When it calls the copy method it only has one node in it, so it says that head is not NULL as expected, but for some reason when it tries to reference head->left
it segfaults.
Any help would be greatly appreciated. :)
EDIT: I didn't know this until one of the people who answered pointed it out, but in the copy constructor, one need to initialize everything to NULL first before attempting to copy. So my problem was solved (for the most part) when I changed my constructor to be the following
BST::BST(const BST & other) : 开发者_JAVA技巧root(NULL), size(0){
First comment: You should probably clear the object's data in the copy if the other object has data or not. If the other object is empty, then the copy should make this object empty too.
Second comment: I cannot tell from your question, but I expect that head->left or head->right was not set to NULL properly during construction. An invalid but not NULL value would explain getting past the if (head == NULL)
check.
In BST::copy it seems odd that your check for NULL is not on the same object as Clear() is called on. There's not enough code given for me to say for sure, but shouldn't it be:
if (root != NULL) {
Clear();
}
Then you may also need to check other.root != NULL for subsequent code you haven't posted.
But as a general rule, Clear() should be made safe to call either way. You should simply check for NULL inside Clear().
Try after
delete head;
head = NULL;
and make sure left and right are set to NULL in the constructor.
精彩评论