3

I'm attempting to build a suffix tree in C++ as part of an assignment on gene sequencing

void Tree::insert(string ins)  
{  
  Node* iterator = chooseBranch(root, ins.at(0));  
  string temp;  
  for(int i=0; i<100; i++)  
    {  
      if(iterator->data=="")  
.
.
.

chooseBranch() is a function to pick which of 4 children to go to, and I'm attempting to check if this Node already exists. My Node class is:

struct Node{  
  Node();  
  string data;  
  Node* A;  
  Node* G;  
  Node* C;  
  Node* T;  
};

This if statement is giving me a segfault, which I used gdb to backtrack to:

#0  0x0000003ce249bbd6 in std::string::compare () from /usr/lib64/libstdc++.so.6
#1  0x000000000040185b in std::operator==<char, std::char_traits<char>, std::allocator<char> > ()
#2  0x0000000000401305 in Tree::insert ()
#3  0x00000000004016d4 in Tree::Tree ()
#4  0x00000000004010a2 in main ()

What is wrong with this form of NULL checking/how else could I check if the Node has no data?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Jesse Welch
  • 63
  • 2
  • 6
  • It doesn't look like you are checking for NULL at all - you are just dereferencing the pointer "iterator". Maybe modify your if statement to "if(iterator && iterator->data.empty())". Incidentally, your input string "ins" might be empty, in which case ins.at(0) will throw an exception. – Matt Curtis Feb 23 '10 at 03:20
  • why not use this http://code.google.com/p/patl –  Feb 23 '10 at 03:22
  • BTW, have you seen Mark Nelson's famous article in DDJ? http://marknelson.us/1996/08/01/suffix-trees/ – San Jacinto Feb 23 '10 at 03:26

1 Answers1

2

It doesn't look like you are checking the pointer iterator for NULL at all, you are simply dereferencing it (which will cause drama if it is NULL).

Here's a sample to try, with the check for NULL hoisted out of the for loop:


void Tree::insert(string ins)
{
    Node* iterator = chooseBranch(root, ins.at(0));
    if (iterator)
    {
        string temp;
        for(int i=0; idata=="")
...
Matt Curtis
  • 23,168
  • 8
  • 60
  • 63