简体   繁体   中英

segmentation fault 11 in c binary search tree

I am getting a segmentation fault when trying to print the nodes in my binary tree. It looks to be an issue with the third node. I have searched google and stack overflow for hours but I can not understand what the problem is. I am trying to teach myself data structures in C and am very much a novice so I may be doing something in a frowned upon way.

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
  int data;
  struct node *left;
  struct node *right;
} Node;

typedef struct
{
  Node *root;
} BinarySearchTree;

void printInOrder(Node *);
void addNode(Node *, Node *);

int main (void)
{
  BinarySearchTree tree;
  BinarySearchTree *tree_ptr = &tree; 
  Node n1, n2, n3;

  n1.data = 1;
  n2.data = 2;
  n3.data = 3;

  Node *n1_ptr = &n1;
  Node *n2_ptr = &n2;
  Node *n3_ptr = &n3;

  tree_ptr->root = n1_ptr;

  addNode(tree_ptr->root, n2_ptr);
  addNode(tree_ptr->root, n3_ptr);
  printInOrder(tree_ptr->root);
}

void printInOrder(Node *root)
{
  if (root == NULL)
  {
    return;
  } else
  {
    printInOrder(root->left);
    printf("%i\n", root->data);
    printInOrder(root->right);
  }
}

void addNode(Node *root, Node *node)
{
  if (node->data < root->data)
  {
    if (root->left == NULL)
    {
      root->left = node;
    } else
    {
      addNode(root->left, node);
    }
  } 

  else if (node->data > root->data)
  {
    if (root->right == NULL)
    {
      root->right = node;
    } else
    {
      addNode(root->right, node);
    }
  }
}

output:

1
2
Segmentation fault: 11

There doesn't seem to be an issue with any but the third node. If I comment out the line that adds the second node I get the same error (with only 1 being printed, obviously).

Your initialization is incomplete

  n1.data = 1;
  n2.data = 2;
  n3.data = 3;

should also set the pointers

  n1.data = 1;
  n1.left = NULL;
  n1.right = NULL;

  n2.data = 2;
  n2.left = NULL;
  n2.right = NULL;

  n3.data = 3;
  n3.left = NULL;
  n3.right = NULL;

Problem is occurring because you are not initializing all the member of structure Node type variable.

I would suggest, you should write a function to initialize the Node type variable, like this:

void init_node(Node * nodeptr, int data)
{
        nodeptr->data = data;
        nodeptr->left = NULL;
        nodeptr->right = NULL;
}

and in your main() (or from where ever you want to initialize) you can simply do:

  init_node(&n1, 1);
  init_node(&n2, 2);
  init_node(&n3, 3);

With this, you will never miss assigning NULL to left and right pointer during initialization of Node type variable and chances of the error occurring because of it will be reduced to a greater extent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM