遇到“ SIGSEGV”细分错误,不确定原因

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

我的程序要求我创建一个二叉搜索树,它也是一个集合。我已经准备好将项目插入其中并使其正常工作,但是当我尝试递归获取树的大小(也就是有多少个节点)时,我的问题就来了。以下是我认为重要的所有代码。

struct SetNode
{
    T data;
    SetNode<T>* left;
    SetNode<T>* right;

    SetNode(const T& value);
};


//Set based on a BST
template <class T>
class MySet
{
private:
    SetNode<T>* root;

public:

    //constructor, insert function, "contains" function declared here

    //get number of items contained
    int size() const;

    int sizeHelper(SetNode<T>* curNode) const;
}

template<typename T>
int MySet<T>::size() const {
    if (root == nullptr)
        return 0;
    else
        return this->sizeHelper(root);
}

template<typename T>
int MySet<T>::sizeHelper(SetNode<T>* curNode) const {
    return 1 + sizeHelper(curNode->left) + sizeHelper(curNode->right);
}

我声明了main并尝试用Set<string> setA调用size后,在setA.size()中出现了问题。从调试器中,我已经看到这会导致上述SIGSEGV错误。我可以更改sizeHelper的声明,甚至在需要时可以将其删除,但是除其中的代码外,size必须保持原样。 sizeHelper应该是非成员函数吗?删除const不起作用。

c++ set binary-search-tree nodes
1个回答
0
投票

您的sizeHelper是一个没有退出条件的递归函数,您只需要继续从给定的节点读取leftright字段,但就不会检查它们是否为nullptr。如果您确实通过了nullptr,则说明您有UB,并且可能有段错误。

为了避免这种情况,您需要像这样添加退出条件。

template<typename T>
int MySet<T>::sizeHelper(SetNode<T>* curNode) const {
    if (curNode == nullptr) {
        return 0;
    }
    return 1 + sizeHelper(curNode->left) + sizeHelper(curNode->right);
}
© www.soinside.com 2019 - 2024. All rights reserved.