Bubibob
Bubibob

Reputation: 191

this -> m_xy was a nullptr

So as my first c++ program I wanted to make a little binary tree but after entering the first value after the root:

Exception thrown: write access violation.

this->m_left was nullptr.

My test input: decreasing int numbers.

My code:

#include<iostream>

class BinaryTree
{
public:
    BinaryTree *m_left;
    int m_key;
    BinaryTree *m_right;

    void insert(int value)
    {
        BinaryTree son;

        if (value <= m_key)
        {
            if (m_left == NULL)
                *m_left = { NULL, value, NULL };  //Error
            else
            (*m_left).insert(value);
        }
        //uniportant stuff ...
     }

     //unimportant stuff
};

int main()
{
int rootValue(0);
std::cout << "Enter a value for the root: ";
std::cin >> rootValue;
std::cout<<std::endl;

BinaryTree root = { NULL, rootValue, NULL };

int leafValue(1);
std::cout << "Enter a value for the leaf or enter 0 to finish: ";
std::cin >> rootValue;
while (leafValue != 0)
{
    root.insert(leafValue);
    std::cout << "Enter a value for the leaf or enter 0 to finish: ";
    std::cin >> rootValue;
    std::cout << std::endl;
}

root.print();

return 0;

}

Upvotes: 1

Views: 576

Answers (2)

Christophe
Christophe

Reputation: 73456

When you create your root node, you create a local BinaryTree object.

When you then insert your first value, m_left is NULL, in the following branch:

if (m_left == NULL)
   *m_left = { NULL, value, NULL };  // Assignment to a NULL pointer.

What happens? You de-reference a null pointer to copy an object. At this point the behaviour is undefined and doomed to fail.

Before assigning anything to the de-referenced pointer, *m_left, the pointer must point to a valid object.

You can correct the assignment as follows:

  m_left = new BinaryTree{ NULL, value, NULL };

Upvotes: 3

Bubibob
Bubibob

Reputation: 191

Ok, problem solved. Simply changed

       *m_left = { NULL, value, NULL };

into

        m_right = new BinaryTree;
        (*m_right).m_left = NULL;
        (*m_right).m_key = value;
        (*m_right).m_right = NULL;

thx Niall

Upvotes: 1

Related Questions