I am attempting to create a BST using linked lists. I am trying to traverse my tree going left or right when appropriate until I find a null then I try to create a node and give a value at that position.
Now I get the error
Segmentation fault (core dumped)
from this code(the logic may not be correct as this is a work in progress)
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
void traverseIn(Node *node, int val);
int main()
{
int numOfNodes;
cout << "number of nodes ";
cin >> numOfNodes;
for(int i = 0;i<numOfNodes;i++){
struct Node *root;
int data;
cout << "data ";
cin >> data;
root->data = data;
traverseIn(root,data);
}
}
void traverseIn(Node *node , int val){
if (node == NULL){
node->data = val;
return;
}
//go leftdat
if (val <= node->data) {
cout << "\nleft " << val<<" "<< node->data;
traverseIn(node->left,val);
}
else if(val > node->data){
//go right
cout << "\nright " << val<<" "<< node->data;
traverseIn(node->right,val);
}
cout << node->data << " ";
}
sample output
number of nodes 5
data 12
left 12 12
Segmentation fault (core dumped)
What I want to know is
1) how can I debug this error as I often come across it. I am using VS Code in Ubuntu using the default compiler it came with and the C/C++ extensions from microsoft but when I attach a break point, I get just the call stack. How can I set it up so that I can step through like I would a java program.
2) How can I make C++ print out meaningful error messages rather than just seg fault message. For example I would like to know what line in the program is at fault(although it is obvious in this example).
3) How can I fix this error.
I have read the xkcd meme and the What is a segmentation fault?