samedi 9 novembre 2019

SIGSEGV for Second Identical toString Calls

To summarize:

  • I am creating a depth-first toString() method for a Trie
  • My first call to toString works perfectly, but any identical second call to toString edits the Trie terribly.

Here I have a Trie class defined as:

Trie.h:

class Trie {  
  char data;
  Trie* kids;
  Trie* sibs;
  Trie* prev;
...
}

The depth-first toString method is defined as:

Trie.cpp:
std::string Trie::toString() {

  std::string results{data ,'\n'};

  if (kids != nullptr) {
    results += kids->toString();
  }
  if (sibs != nullptr) {
    results += sibs->toString();
  }

  return results; 

}

I then run this test:

int main(void) {
  Trie* t1 = new Trie('A') ;
  assert(t1->toString() == "A\n");
  assert(t1->addChild('b')); //Essentially sets t1->kids to new Trie('b')
  std::cout << t1->toString() << std::endl; //Passes
  std::cout << t1->toString() << std::endl; //SIGSEGV
}

The first print out works exactly as planned: prints "A\nb\n"

which is means the tree looks like this:

(65) A 
   |
(98) b

but the second print out gives me a SIGSEGV and GDB shows that the Trie is now set to a pattern like this:

                (65) A
        /          |           \
(-128) \200 — (-13) \363  — "Cannot access.."
      |            |
  (49) 1    —  "Cannot access..."

Any idea about why the second print statement edits t1?

Aucun commentaire:

Enregistrer un commentaire