构造函数内部变量的定义会导致分段错误

问题描述 投票:-1回答:1

我正在编写一个集合的实现,使用带有sentinal _head和_tail节点的双向链表。每个节点由Elem结构定义。我只包含导致问题的代码部分:

set.h

#include <string>
using namespace std;
class Set {
    public:
        Set();
        ~Set();
    private:
        struct Elem {
            string info;
            Elem *prev, *next;
        };
        Elem *_head, *_tail;
        int _size;
};

set.cpp

#include "set.h"
using namespace std;
Set::Set() {
    _size = 0;  // Segmentation fault from this
    _head = new Elem;
    _tail = new Elem;
    _head = nullptr;    // Segmentation fault from this
    _tail = nullptr;    // Segmentation fault from this
    _head->next = _tail;
    _tail->prev = _head;
}
Set::~Set() {
    while (_head->next != _tail) {
        _head->next = _head->next->next;
        delete _head->next->prev;
    }
}

setTest.cpp

#include "set.h"
using namespace std;
int main() {
    Set s1;
}

当我运行测试驱动程序“setTest.cpp”时,上面的代码导致分段错误。我做了一些调试,并隔离了导致错误的部分。它似乎是定义_size,_head和_tail变量的三行。

为什么构造函数中这些变量/指针的定义会导致分段错误?

c++ struct linked-list segmentation-fault set
1个回答
0
投票

问题是由_head和_tail设置为null引起的。通过将它们设置为null然后尝试访问它们不再“存在”的prev和next指针。

© www.soinside.com 2019 - 2024. All rights reserved.