> but I already combined a constructor in the insert function.
the problem is with the node created in main(). Inspect it
root = {data = "", left = garbage, right = garbage} |
When you call the insert() function you are doing
insert(&root, word);
*
Now see what happens inside the function
1 2 3 4 5 6 7 8 9
|
void BinNode::Insert(BinNode *&root, string word)
{
if(root==NULL) //false
//...
if(word > root -> data) //data is empty, false
Insert (root -> right, word);
if(word < root -> data) //true
Insert (root -> left, word); //gets called
}
|
So you called the function again, now passing `root->left'. But `root->left' has garbage, so when you try to do `root->left->data' you invoke undefined behaviour
> I want to repeat that it already worked when I used Visual Studio
undefined behaviour is undefined
you don't initialize your variables, they have garbage. `0' is as good value for garbage as any other.
> And you are right about memory leakage, but even after I insert "delete root" before "return;"
No, you must delete the object when you finish using it.
By instance
1 2 3 4 5
|
//the parent dies, so it takes its children with it
BinNode::~BinNode(){
delete left;
delete right;
}:
|
Another thing that you may do is to separate the tree from the nodes, the client doesn't need to know about the node class
1 2 3 4 5
|
class tree{
BinNode root;
public:
insert(std::string word);
};
|
* The object is irrelevant, you don't use state in your function
You actually use `ptr' that holds the value of &root. And you never modify `ptr'