Syed
Syed

Reputation: 530

Binary tree produce Segmentation Fault

I'm new to C and want to get started by coding a simple binary tree. There are problems in both the push and traverse functions but it's been two days me figuring out the program. When I compiles and execute the program it shows segmentation fault. The code is given below and any help would be appreciated. Thanks

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

typedef struct Node
{
  struct Node* right;
  struct Node* left;
  int* value;
} Node;

Node* init()
{
  Node* t = (Node*) malloc(sizeof(Node));
  t->left = NULL;
  t->right = NULL;
  t->value = NULL;
  return t;
}

int traverse(Node* tree)
{
  printf("value : %d\n", *(tree->value));
  if (tree->left != NULL) {
    traverse(tree->left);
  } else if (tree->right != NULL){
    traverse(tree->right);
  }
}

void push(Node* n, int val)
{
  if (n->value == NULL)
  {
    *(n->value) = val;
  } else if (n->left == NULL && val < *(n->value)) {
    n->left = init();
    push(n->left, val);
  } else if (n->right == NULL && val > *(n->value)) {
    n->right = init();
    push(n->right, val);
  }
} 

int main(int argc, char const *argv[])
{
  srand(time(NULL));
  Node* tree = init();

  for (unsigned int i = 0; i < 20; ++i)
  {
    int val = rand() % 10;
    push(tree, val);
    printf("%d\n", val);
  }

  traverse(tree);
  printf("%s\n", "End Of Program!");
  return 0;
}

Upvotes: 1

Views: 47

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 224310

The value member of the Node type is never set to any value other than NULL. Since its value is a null pointer, using the statement *(n->value) = val; is improper; it attempts to dereference the null pointer.

If you want value to point to an int, you must allocate memory for an int and set value to the address of that memory. If you want value to be an int, you must change its declaration, and the code that uses it.

Upvotes: 1

jmq
jmq

Reputation: 1591

You never allocate space for value. Change the definition to an integer.

typedef struct Node
{
  struct Node* right;
  struct Node* left;
  int value;
} Node;

and then

n->value = val;

and

printf("value : %d\n", tree->value);

Upvotes: 2

Related Questions