mardi 4 juin 2019

Segmentation fault during after calling reset on unique_ptr

I'm getting a segmentation fault while calling reset on unique_ptr:

Node* tree::left_rotate(Node* node) {
    Node* temp = node->right.get();
    node->right.reset(temp->left.get());
    temp->left.reset(node); // **Here is segmentation fault heppens**
    if(node->right.get()) {
        node->right->parent = node;
    }
    temp->parent = node->parent;
    if(node->parent) {
        if(node == node->parent->left.get()) {
            node->parent->left.reset(temp);
            node->parent = node->parent->left.get();
        } else if(node == node->parent->right.get()) {
            node->parent->right.reset(temp);
            node->parent = node->parent->right.get();
        }
    }
    return temp;
}

Node has the following structure:

class Node {
    public:
        int data;
        Node* parent;
        std::unique_ptr<Node> left;
        std::unique_ptr<Node> right;
    public:
        Node() : data(0) {          
        }
        explicit Node(int d) : data(d),
                               parent(nullptr),
                               left(nullptr),
                               right(nullptr) {}        
};

g++ reports:

Thread 1 received signal SIGSEGV, Segmentation fault. 0x00404ae5 in std::unique_ptr >::~unique_ptr ( this=0xfeeefefa, __in_chrg=) at C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/unique_ptr.h:273 273 if (__ptr != nullptr)

The report from one stack-frame upper:

#2  0x004047e8 in std::default_delete<Node>::operator() (this=0xfe1de4,
    __ptr=0xfeeefeee)
    at C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/unique_ptr.h:81
81              delete __ptr;

So it seems here is double deletion. How this issue can be solved? Maybe it worths to have a temp pointer as a shared_ptr?

Aucun commentaire:

Enregistrer un commentaire