0

I am implementing a binary tree and do some insertion and search one of the inserted values. But I am getting memory error saying "Thread 1: EXC_BAD_ACCESS(code=1, address=0x0)

my binary tree is like the following

  struct node
  {
        int data;
        node* left = nullptr;
        node* right = nullptr;

        explicit node(int data) : data(data) {};
  };

my insertion function is like the following

  node* insertion(node* root, int value)
  {
        if (root != nullptr) return new node(value);

        if (value < root->data)
        {
              root->left = insertion(root->left, value);
        }
        else
        {
              root->right = insertion(root->right, value);
        }

        return root;
  }

My Binary Search function is like the following

  node* binary_search(node* root, int value)
  {
        if (root == nullptr || root->data == value)
        {
              return root;
        }

        if (value < root->data) return binary_search(root->left, value);
        else return binary_search(root->right, value);
  }

so in main function, I inserted several values to root and try to find one value 13 and print them out to test binary search tree function does its job to search, but as you see I am getting errors. It compiles though.

  struct node* root = new node(NULL);
  root->data = 10;
  root = insertion(root, 1);
  root = insertion(root, 11);
  root = insertion(root, 2);
  root = insertion(root, 12);
  root = insertion(root, 3);
  root = insertion(root, 13);
  root = insertion(root, 5);
  root = insertion(root, 20);
  root = insertion(root, 7);
  root = insertion(root, 15);

  auto temp1 = binary_search(root, 13);
  cout << "Did you find 13? : " << temp1->data << endl; 
   // Here I am getting that error.
1
  • 1
    Well, something is null. You should use the debugger (or print statements) to find out what. Commented Aug 24, 2013 at 0:05

1 Answer 1

1

Your insertion() code is wrong. You probably meant to use

if (root == nullptr) { ... }

As is, your tree will contain just one node! When you then search for your values, it doesn't find the value and returns nullptr. This value then get dereferenced because you don't check if you found the value but assume that it is there.

Sign up to request clarification or add additional context in comments.

1 Comment

OMG I never thought about that. Thanks a million!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.