Reputation: 5
friends. So I'm creating a Binary Search Tree Class in ubuntu using vim as my editor, and when I run my program I always get a segmentation fault(core dumped) error. The weird thing is that when I run this program on NetBeans, it worked perfectly. this is my code
#include <iostream>
using namespace std;
class BST
{
struct node {
int data;
node* left;
node* right;
};
private:
node* root;
node* addHelper(node* temp, int data)
{
if(temp == NULL)
{
temp = new node;
temp->left = temp->right = NULL;
temp->data = data;
return temp;
}
if(data < temp->data)
{
temp->left = addHelper(temp->left, data);
}
else if(data > temp->data)
{
temp->right = addHelper(temp->right, data);
}
return temp;
}
void printHelper(node* cur)
{
if(cur == NULL)
{
return;
}
else {
printHelper(cur->left);
cout << cur->data << " ";
printHelper(cur->right);
}
}
public:
void add(int value)
{
root = addHelper(root, value);
}
void printInorder()
{
printHelper(root);
}
};
int main()
{
cout << "Second Test, linux runnning sucsesfully"<<endl;
BST mytree;
mytree.add(20);
mytree.add(25);
mytree.add(10);
mytree.add(22);
mytree.add(15);
mytree.add(12);
mytree.add(23);
mytree.printInorder();
return 0;
}
I already use gdb to debug, and it pointed me an error on the printHelper function but I can't see the error. if you know how to fix this please help me. thank you in advance
Upvotes: 0
Views: 346
Reputation: 815
Certianly yes the problem is the data member root
is used and not initialized
Solution for the problem
public:
BST(){
root = new node();
}
If at all the use case demands some more operations in the constructor you can also use the initializer list which is good in terms of readability. Just an add-on you should always initialize const
and reference
using the initializer list.
Or using the initializer list
public:
BST(node* root):root(root){
//Any other initialization /Operation
}
Or give it a NULL (or nullptr, in the most recent C++ standard).
public:
BST() : root(NULL) { }
Our default ctor here makes it NULL (replace with nullptr if needed), the second constructor will initialize it with the value passed..
Upvotes: 1
Reputation: 61
The fix is just initialize the root as NULL . [Do not allocate anything there.] constructor must be like below
BST() {
root = NULL;
}
Also root shall be created only once We should not be change it ever. So change the code like below
if (root == NULL) {
root = addHelper(root, value);
} else {
addHelper(root, value);
}
Upvotes: 0
Reputation: 1736
You don't initialize your root
variable before using it. You can initialize it in a constructor as the following:
public:
BST(){
root = new node();
}
Upvotes: 0