Here is my Node class.
class Node
{
private:
public:
T data;
Node<T>* left;
Node<T>* right;
Node(T dat) : data(dat), left(NULL), right(NULL)
{}
};
Here is my insert function, defined in my Btree class:
public:
Node<T>* root;
Btree() : root(NULL){}
void insert(T data, Node<T>* parent)
{
if( !parent )
{
parent = new Node<T>(data);
return;
}
else if(data < parent->data)
{
insert(data, parent->left);
}
else if(data > parent->data)
{
insert(data, parent->right);
}
}
};
Here is my main function:
int main()
{
Btree<int> tree;
tree.insert(5, tree.root);
cout << tree.root->data << endl;
tree.insert(6, tree.root);
cout << tree.root->right->data << endl;
}
When I run, I get a seg fault.
I think it is because the pointer variable parent is passed by value, so when I create a new Node that is pointed to by parent, once I exit the insert function I lose it? Does that mean I have to use a double pointer here?
Can someone give me a thorough explanation about what’s going on in memory that is making this not work out as planned. Is my diagnosis correct here or is there something else wrong?
When I pass tree.root as the second parameter to insert, I am passing a Node*, I know that much. Now, even if it is passed by value, will it not be the same address that I passed from the invoking main function. So when I say parent (which is the address which I passed from main, tree.root) = new Node, should that not create a new Node on the heap that at the address of parent, aka the address of tree.root? Why does passing by value fudge this up?
The problem with passing by value in this case is that all assignments made to the formal argument inside the function are not visible to the caller. Therefore, this assignment
has no effect on the
tree.rootin the caller:The value of the
parentpointer in the function is changed, and then promptly discarded; tree’srootremainsNULL.A fix to this problem would be passing a pointer to a pointer, like this: