Need help fixing a segmentation fault (core dumped)

Lolo

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

Liger

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..

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related