【问题标题】:Core dump while implementing binary tree travers实现二叉树遍历时的核心转储
【发布时间】:2020-04-10 11:45:00
【问题描述】:

我试图用人来实现二叉树。 任何人都有父亲和母亲。 在我的 main() 函数中,它运行良好,直到我将人添加到我的第一个“X”的父亲。 我的 main 在第 4 次 addFather("Y","F") 调用中出现 Aborted (core dumped) 错误,我无法意识到我的错。

Person& findPerson(Person* root, string child_name){
    if(root == nullptr) throw exception();
    else if(root->name.compare(child_name) == 0) return *root;
    else{
        if(root->father == nullptr)return findPerson(root->mother, child_name);
        else if(root->mother == nullptr)return findPerson(root->father, child_name);
        else {
            return findPerson(root->mother, child_name);
            return findPerson(root->father, child_name);
        }

    }
}

family::Person::Person(string person_name){
    name = person_name;
    father = nullptr;
    mother = nullptr;

};

family::Person::Person(string person_name, bool is_male){
    name = person_name;
    father = nullptr;
    mother = nullptr;
    isMale = is_male;

};



// TREE
family::Tree::Tree(string name){
    root = new Person(name);
};

family::Tree& Tree::addFather(string child, string father){
    Person& child_found = findPerson(root, child);
    Person* f = new Person(father, true);
    child_found.father = f;

    return *this;
    };


family::Tree& family::Tree::addMother(string child, string mother){
    Person& child_found = findPerson(root, child);
    Person* f = new Person(mother, false);
    child_found.mother = f;
    return *this;
    };
int main(){
    Tree t("X");

    t.addFather("X","Y");
    t.addMother("X", "Z");
    t.addFather("Z", "W");
    t.addFather("Y","F");
    return 0;
}

【问题讨论】:

  • 请注意,一旦函数返回,它就会退出。你有return findPerson(root->mother, child_name); 然后return findPerson(root->father, child_name); 在连续的行上。第二个 return 永远不会执行。
  • 是的,在 findPerson() 中
  • 那么我怎样才能让其中两个执行呢?我可能会导致一些递归失败。
  • 我认为您应该更改签名以返回指针而不是引用。然后你可以比较返回到 nullptr 的指针。在这种情况下,您可能希望摆脱 if(root == nullptr) throw exception(); 并返回 nullptr if root == nullptr
  • 实际上您的解决方案有效!我的错误的解释是什么?

标签: c++ error-handling tree


【解决方案1】:

您的代码需要工作,但一个提示是,如果您抛出异常,您必须catch it。在 C++ 中没有很好地定义未捕获异常时会发生什么,因此这很可能是您的问题。

所以,例如,

if(root->father == nullptr)return findPerson(root->mother, child_name);

不检查母亲和父亲是否都为空。如果是,它将使用 nullptr 调用 findPerson。这将使函数抛出。

作为提示,在 linux 系统上,查找这些问题的最佳方法是使用 gdb。命令“catch throw”后跟“start”和“continue”,将捕获任何抛出的异常。然后“bt”会告诉你你是如何到达那里的。 GDB(让我们面对现实)是一个糟糕的回归,对于大多数初学者来说是难以理解的,但是,就像 vi 一样,至少了解基础知识是一项很好的技能。

快速入门指南。 https://beej.us/guide/bggdb/

【讨论】:

    猜你喜欢
    • 2012-01-01
    • 2022-11-11
    • 2011-02-08
    • 2014-02-12
    • 2015-06-23
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多