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) : 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.