BST Dostávám chybu segmentace

hlasů
3

EDIT: běží to přes gdb dává

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

Potřebuji pomoc s mým prvním BST kódu Dostávám chybu segmentace, myslím, že se jedná o únik paměti? pokud ano, i dont vědět, kde / jak opravit tady jsou kódy, které myslím, že jsou příčinou problému. Je to proto, že jsem dont mít kopii konstruktor ještě nastavit ??

soubor tree.cpp

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;
}
Položena 27/04/2011 v 14:09
zdroj uživatelem
V jiných jazycích...                            


2 odpovědí

hlasů
2

Vidím nějaký možný segfault whenn Dívám se na zvolenou metodu. Jen myslet na případy hran.

Co se tu stalo?:

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

nebo

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

Fix těchto případů a pokračovat.

Odpovězeno 27/04/2011 v 14:19
zdroj uživatelem

hlasů
2

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;
}

Ty jsou vždy používat rootmísto currentRoot, takže nemáte opravdu sestoupit na strom a dostane StackOverflow v určitém okamžiku. Také vám chybí na zkontrolovat, zda je currentRootIS NULL, protože pokud jej přístup poté, dostanete pěknou segfault (to je to, co @tgmath mysli).

bool Tree::findKey(string& s, int k, Node* currentRoot)
{
    if(currentRoot == NULL)
        return false;
    // as before ...
}
Odpovězeno 27/04/2011 v 14:24
zdroj uživatelem

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more