【问题标题】:segmentation fault in binary search tree二叉搜索树中的分段错误
【发布时间】:2017-02-15 05:05:25
【问题描述】:
/*
Here is the piece of code causing segmentation fault
*/

int search_for_data(T_NODE head, int data){
    while(head){
        if( head->data > data)
            head = head->left;
        if( head->data < data)
            head = head->right;
        else
            return head->key;
      }
return -999999;// in case the node is not found
}

代码似乎对少数几个值抛出了分段错误,但对其他值却很好。我尝试搜索 22 并且出现分段错误。

【问题讨论】:

    标签: segmentation-fault binary-search-tree


    【解决方案1】:

    if之前缺少else

        if( head->data > data)
            head = head->left;
        else if( head->data < data) /* this line */
            head = head->right;
        else
            return head->key;
    

    使用原始代码,它评估第一个if,然后立即评估第二个,尽管head 可能在第一个if 之后变成NULL

    【讨论】:

    • 非常感谢!!这真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多