【问题标题】:Search - BST- getting segmentation fault搜索 - BST - 得到分段错误
【发布时间】:2017-07-20 18:07:57
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
    int data;
    struct node *right, *left;
};
struct node *root = NULL;

int flag = 0;

void insert(int val){
    struct node *t, *p;
    t = (struct node*)malloc(sizeof(struct node));
    t->data = val;
    t->left = NULL;
    t->right = NULL;
    p = root;
    if( root == NULL ){
        root = t;
        return;
    }
    struct node *curn = root;

    while(curn){
        p = curn;
        if(t->data > curn->data){
            curn = curn->right;
        }
        else{
            curn = curn->left;
        }
    }
    if(t->data > p->data){
        p->right = t;
    }
    else{
        p->left = t;
    }
}
int search(int val){

    if(root->data == val){
        return 1;
    }
    struct node *curn;
    curn = root;
    while(curn){
        if(curn->data < val){
            curn = curn->right;
            if(curn->data == val){
                return 1;
            }
        }
        if(curn->data > val){
            curn = curn->left;
            if( curn->data == val ){
                return 1;
            }
        }
    }
    return 0;
}
int main(void){
    char opt[5] = "yes";
    int val, sear;
    while(1){
        printf("Enter the key number:\n");
        scanf("%d",&val);
        insert(val);
        printf("Do you want to create another junction?\n");
        scanf("%s",opt);        
        if(strcmp(opt,"yes") == 0){
            continue;
        }
        if(strcmp(opt, "no") == 0){
            printf("Enter the key to be searched\n");
            scanf("%d",&sear);
            flag = search(sear);
            if(flag == 1){
                printf("%d found",sear);
                return 0;
            }
                printf("%d not found",sear);
                return 0;
        }
    }

}

在搜索过程中,如果搜索键可用,则显示找到键,不会抛出任何错误。

但是如果搜索键不存在意味着它会抛出一个错误segmentation fault(core dumped), 为什么这个分段错误出现在我的代码中?

【问题讨论】:

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


【解决方案1】:

你的代码在这里:

if(curn->data < val){
    curn = curn->right;
    if(curn->data == val){
        return 1;
    }
}
if(curn->data > val){
    curn = curn->left;
    if( curn->data == val ){
        return 1;
    }
}

curn = curn-&gt;left; 在这一行之后,curn 可能为 NULL,因此curn-&gt;data 将引发分段错误。您想在ifelse if 控件中检查curn-&gt;data == val,如下所示:

if(curn->data < val){
    curn = curn->right;
}
else if(curn->data > val){
    curn = curn->left;
}
else {
    return 1;
}

无需检查curn-&gt;data == val,因为如果它不小于或大于,它必须等于。

【讨论】:

    【解决方案2】:

    在您的while 循环中检查curn 是否不是NULL if(!curn &amp;&amp; curn-&gt;data &lt; val)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多