kingcong3
kingcong3

Reputation: 193

BST keep getting Segmentation fault

EDIT: running it through the gdb gives

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400e4c in Tree::findKey(std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int, Tree::Node*) ()

Need some help with my first BST code, I keep getting a segmentation fault, i think that it is a memory leakage? if so i dont know where/ how to fix here are the codes that i think are causing the problem. Is it because I dont have a copy constructor set up yet??

tree.cpp file

Tree::Tree()
{
  root = NULL;
}

bool Tree::insert(int k, string s)
{
  return insert(root, k, s);
}
//HELPER Call find data with key function
bool Tree::findKey(string& s, int k)
{
    return findKey(s, k, root);
}
bool Tree::insert(Node*& currentRoot, int k, string s)
{
  if(currentRoot == NULL){
    currentRoot = new Node;
    currentRoot->key = k;
    currentRoot->data = s;
    currentRoot->left = NULL;
    currentRoot->right = NULL;
    return true;
  }
  else if (currentRoot->key == k)
    return false;
  else if (currentRoot->key > k)
    return insert(currentRoot->left, k, s);
  else
    return insert (currentRoot->right,k, s);
}
bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if (currentRoot->key == k){
        s = root->data;
        return true;
    }
    else if (root->key < k)
        return findKey (s, k, root->right);
    else if (root->key > k)
        return findKey (s, k, root->left);
    else
        return false;
}

main.cpp

int main()
{
string sout;
  Tree test;
    test.insert(1, "a");
    test.insert(2, "b");
    test.insert(3, "c");
    test.findKey(sout, 3);
    cout<<sout<<endl;
  return 0;
}

Upvotes: 3

Views: 244

Answers (2)

Xeo
Xeo

Reputation: 131789

bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if (currentRoot->key == k){
        s = root->data;
        return true;
    }
    else if (root->key < k)
        return findKey (s, k, root->right);
    else if (root->key > k)
        return findKey (s, k, root->left);
    else
        return false;
}

You are always using root instead of currentRoot, so you don't really descend down the tree and will get a stackoverflow at some point. Also, you're missing the check if the currentRoot is NULL, because if you access it then, you'll get a nice segfault (this is what @tgmath meant).

bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if(currentRoot == NULL)
        return false;
    // as before ...
}

Upvotes: 2

tgmath
tgmath

Reputation: 13531

I see some possible segfault whenn I look at your method. Just think of edge cases.

What happens here?:

Tree test; 
test.findKey(sout, 3);

or

Tree test;
test.insert(1, "a");
test.findKey(sout, 3);

Fix these cases and proceed.

Upvotes: 2

Related Questions