0xC0000005: Access violation reading location 0xCDCDCDCD

-1

I have been having an issue with a Binary Search Tree that I am making for a larger project.

There is a node:

template <class Key, class Value>
struct Node
{
public:
    Key key;
    vector<Value> value;
    Node* leftNode;
    Node* rightNode;

    Node(Key k, Value v)
    {
        key = k;
        value.push_back(v);
    }
};

These nodes are being stored into the BST.

The error occurs in the Insertion function of the BST:

template <class Key, class Value>
void BinarySearchTree<Key, Value>::insert(const Key &key, const Value &value)
{
    insert(root, key, value);
}


template <class Key, class Value>
void BinarySearchTree<Key, Value>::insert(Node<Key, Value> *&node, const Key &key, const Value &value)
{
    if (node == nullptr)
        node = new Node<Key, Value>(key, value);

    // Error occurs here.
    else if (node->key == key)
        node->value.push_back(value);

    else if (key < node->key)
        insert(node->leftNode, key, value);
    else
        insert(node->rightNode, key, value);
}

The first node is inserted into the tree without issue, however the second Insertion call throws the error.

Any help in putting me on the right track would be greatly appreciated.

c++
asked on Stack Overflow Jul 16, 2018 by MattS

2 Answers

3

Your insert code seems to assume that Node::leftNode and Node::rightNode are initialised to nullptr but your constructor doesn't ensure that. Try this

Node(Key k, Value v)
{
    key = k;
    value.push_back(v);
    leftNode = rightNode = nullptr;
}
answered on Stack Overflow Jul 16, 2018 by john
1

Your code isn't initialising leftNode or rightNode. Raw pointer values are not value-initialised if there is no member initialiser for them. std::unique_ptrs are default constructed equal to nullptr

There also doesn't seem to be any cleanup of Nodes

template <class Key, class Value>
struct Node
{
public:
    Key key;
    std::vector<Value> value;
    std::unique_ptr<Node> leftNode;
    std::unique_ptr<Node> rightNode;

    Node(Key k, Value v)
     : key(k), value({v})
    { }
};
answered on Stack Overflow Jul 16, 2018 by Caleth • edited Jul 16, 2018 by Caleth

User contributions licensed under CC BY-SA 3.0