【问题标题】:The Output of this Program in gcc Compiler is Segmentation Fault(core dumped).What i am doing wrong?这个程序在 gcc 编译器中的输出是分段错误(核心转储)。我做错了什么?
【发布时间】:2019-10-09 02:59:58
【问题描述】:

这是一个二叉搜索树实现,我想知道它有什么问题?

#include<iostream>
using namespace std;

struct node
{
    int data;
    node *left;
    node *right;
};

class tree
{
    node *root;
public:
    tree()
    {
        root=NULL;
    }

void insert(node *root,int key)
{
    if(root==NULL)
    {
    root->data=key;
    root->left=NULL;
    root->right=NULL;
    }

    else if(key<root->data)
    {
        node *temp = new node;
        if(root->left==NULL)
        {
            root->left=temp;
            temp->left=NULL;
            temp->right=NULL;
        }
        else
        {
            insert(root->left,key);
        }
    }
    else
    {
        node *temp=new node;
        if(root->right==NULL)
        {
            root->right=temp;
            temp->left=NULL;
            temp->right=NULL;
        }
        else
        insert(root->right,key);
    }
}

void search(node *root,int key)
{
    if(root==NULL)
        cout<<"Tree is Empty";
    else if(root->data==key)
        cout<<"Match Found";
    else if(key<root->data)
        search(root->left,key);
    else
        search(root->right,key);
}

node* getHead()
{
    return root;
}
};

int main()
{
    tree a;
    a.insert(a.getHead(),5);
    a.insert(a.getHead(),3);
    a.insert(a.getHead(),9);
    a.insert(a.getHead(),11);
    a.insert(a.getHead(),7);
    a.search(a.getHead(),11);
    return 0;
}

也许我的实现访问了一些我没有声明的内存。我刚刚创建了一个函数来插入一个节点和一个搜索函数,如果树没有匹配则返回。纠正我做错了什么。输出在我的 g++ 编译器中是分段错误(核心转储)。

【问题讨论】:

  • 你没有在insert里面给root分配内存。
  • @0x499602D2 谢谢。但是为什么我做 node *root=new node; 时它不起作用在我宣布root的课堂上。还有为什么当我搜索它说树为空的任何元素时我的树是空的。

标签: c++ linked-list tree binary-tree binary-search-tree


【解决方案1】:

你的问题出在这部分:

if(root==NULL)
{
    root->data=key;
    root->left=NULL;
    root->right=NULL;
}

您对 root 是否为 NULL 执行测试,然后继续访问 root 的成员,这将导致分段错误。所以,本质上,代码在做:

if(root==NULL)
{
    NULL->data=key;
    NULL->left=NULL;
    NULL->right=NULL;
}

最后一点,最好不要将与成员变量同名的变量传递给函数。它使代码非常难以阅读和调试。因此,将“插入”和“搜索”中的变量“根”更改为“检查节点”或类似的东西。调试代码会容易得多。

【讨论】:

  • 这样做会导致 '->' 的错误基本操作数不是指针。意思是 null 不是指针。
  • 这就是重点。如果 'root == NULL' 为真,则访问 'root' 的成员等同于尝试访问 NULL 中的成员。它仅用于说明目的。更改代码不适合您。
  • 修复代码的第一件事是更改“插入”和“搜索”中的局部变量,使其不使用成员变量名称“root”。之后,你的调试会变得更容易。
猜你喜欢
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 2015-09-29
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多