i'm having a problem with a seg fault, but i'm stumped.
i've found it, but i just do not understand why i get it.
it's in the seventh line of WordTree::insert(const string &).
i have put similar code in the third, fourth and fifth line of main()
and that code doesn't seg fault.
(don't worry, you don't have to count the lines, i have marked them with "//******" and a description)
Code:
/*** COMNDENSED TO SAVE SPACE ***/
#ifndef WORDTREE_H
#define WORDTREE_H
#include <string>
#include <iostream>
using std::cout;
using std::endl;
class WordTree
{
typedef std::string str;
public:
WordTree(const str & = "");
int search(const str &);
int insert(const str &);
void print(void);
private:
WordTree *left;
WordTree *right;
str key;
};
#endif
Code:
#include "WordTree.h"
using namespace std;
WordTree::WordTree(const string &src)
{
key = src;
left = right = 0;
}
int WordTree::insert(const string &src)
{
if(!key.size())
{
key = src;
return 1;
}
// this seg faults
if(src < key){ cout << "test" << endl; }
//*****************
//the real code (i know i can factor this out, and it was to
//begin with, but i expanded it and simpified it to find the seg fault
//...there's no need to fix or correct this code, i'm going to
//revert to my original code. i have only posted it so no one would
//accuse me not giving them the whole code and claim the seg fault is elsewhere.
/*if(src < key)
{
if(left)
{
cout << "CP 2" << endl;
return left->insert(src);
}
else{
cout << "CP 3" << endl;
left = new WordTree();
cout << "CP 4" << endl;
return left->insert(src);
}
}else{
cout << "CP 2.b" << endl;
if(right){
return right->insert(src);
cout << "CP 3.b" << endl;
}
else{
cout << "CP 4.b" << endl;
right = new WordTree();
cout << "CP 5.b" << endl;
return right->insert(src);
}
} */
return 1;
}
//not even called, but if you have extra time, i'd like someone to comment on it if there's a better way (it's untested)
int WordTree::search(const string &src)
{
if(src == key)
return 1;
else
if(src <= key)
if(left)
left->search(src);
else
return 0;
else
if(right)
right->search(src);
else
return 0;
return 0;
}
//called but still segfaults whether it's called or not
void WordTree::print(void)
{
cout << key << endl;
if(left)
left -> print();
if(right)
right -> print();
}
Code:
/********* crappy test file, no need to pick it apart *****/
#include <cstdlib>
#include <iostream>
#include "WordTree.h"
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
WordTree wt("n");
wt.print();
//this doesn't seg fault
string x = "n";
string y = "p";
cout << (x < y) << endl;
//*********************
while(x != "stop")
{
cin >> x;
wt.insert(x);
}
wt.print();
system("PAUSE");
return EXIT_SUCCESS;
}