分段释放指针向量的错误

Segmentation Fault freeing a vector of pointers

本文关键字:错误 向量 指针 释放 分段      更新时间:2023-10-16

编译下面的代码时出现分段错误。当我试图释放指针向量时,这来自于destructor实现。你能帮忙吗?

我还有一个问题。对我来说,我认为我只能删除向量内的指针,向量会自动删除。但是,当指针被删除时,向量可能什么都不包含吗?感谢

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iterator>
using namespace std;
/* ******************************************************* Node ********************************************************* */
template<class T>
class Node
{
    private:
        T _value;
        vector<Node<T>*> children;
    public:
        Node(T value);
        Node(const Node<T>& node);
        void AddChild(Node<T>* node);
        T getValue() const;
        vector<Node<T>*> returnChildren() const;
        ~Node();
};
template <class T>
Node<T>::Node(T value):_value(value)
{
    children.push_back(NULL);
}
template <class T>
Node<T>::Node(const Node& node):_value(node.getValue()), 
                                children(node.returnChildren())
{
}
template <class T>
void Node<T>::AddChild(Node* node)
{
    if (children[0]==NULL){children.pop_back();};
    children.push_back(node);
}
template <class T>
T Node<T>::getValue() const
{
    return _value;
}
template <class T>
vector<Node<T>*> Node<T>::returnChildren() const
{
    return children;
}
template <class T>
Node<T>::~Node()
{
    for (typename vector<Node<T>*>::iterator it=children.begin() ; it!=children.end() ; it++)
    {
        delete *it;
    }
}

int main()
{
    Node<int> n(3);
    Node<int> nn(4);
    n.AddChild(&nn);
    Node<int>* child= new Node<int>(*(n.returnChildren()[0]));
    cout << (*child).getValue() << endl;
}

IMHO基本上有两个错误:1) 在~Node()中,您应该添加检查以查看指向子级的指针是否为null(否则,删除null指针会导致seg错误)2) 在主函数节点中实例化为局部变量(在函数堆栈中,而不是堆中)将在函数退出时自动启动~Node():这意味着另一个seg错误,因为您试图删除两次相同的指针。