0
votes

Here is my code where I am assigning values to node of tree. I am able to assign well till right and left child of tree. But when I try to use left->left child of root, it gives me access violation error.

Unhandled exception at 0x00DE5CC3 in Trees.exe: 0xC0000005: Access violation reading location 0x00000004.

Exactly getting error at line, unique_ptr<node> (r->left->left) = newNode(4);.

I am using unique_ptr, if I use raw pointers, everything works as expected.

Following is my code,

using std::cout;
using std::endl;
using std::unique_ptr;


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

unique_ptr<node> newNode (int i)
{
    unique_ptr<node> n (new node);
    n->data = i;
    n->left = nullptr;
    n->right = nullptr;

    return n;
}

int main(int argc, char* argv[])
{
    unique_ptr<node> r = newNode(1); 
    unique_ptr<node> (r->left) = newNode(2);
    unique_ptr<node> (r->right) = newNode(3);
    unique_ptr<node> (r->left->left) = newNode(4);//this line craches 
    unique_ptr<node> (r->left->right) = newNode(5);
    return 0;
}
1

1 Answers

9
votes
unique_ptr<node> (r->left) = newNode(2);

This doesn't do what you seem to think it does (though it's hard to say exactly what you imagine this to be doing). This is what happens:

  1. A temporary unique_ptr is constructed, initialized with the value of r->left (currently nullptr).

  2. This temporary unique_ptr is reassigned, now holding the value returned by newNode(2).

  3. At the semicolon, the temporary is destroyed; its destructor deletes the pointer it was holding.

In the end, this line is an elaborate no-op. It allocates a piece of memory, then frees it right away. r->left is not modified in any way, and remains nullptr.

Then, r->left->left crashes, since you are trying to dereference a null pointer.


If you hope to get any mileage out of unique_ptr, make node members unique_ptr, as in

struct node
{
    int data;
    unique_ptr<node> left;
    unique_ptr<node> right;
};