【问题标题】:C Structure Linked List Segmentation FaultC结构链表分段错误
【发布时间】:2013-07-09 22:05:57
【问题描述】:

我正在学习 C 中的链表,但我的删除功能有问题。线路出现分段错误:

while(current1 != NULL && (current1->next->data != d))

void delete(int d)
{
    struct list * current1 = head; 
    struct list * current2;

    if (len() == 0)
    { //prtError("empty");
        exit(0);
    }
    if (head -> data == d)
    { 
        head = head -> next;
    }

    //Check if last node contains element
    while (current1->next->next != NULL)
        current1 = current1->next;
    if(current1->next->data == d)
            current1->next == NULL; 

    current1 = head; //move current1 back to front */

    while(current1 != NULL && (current1->next->data != d))
        current1 = current1 -> next; 

    current2 = current1 -> next;
    current1 -> next = current2 -> next; 
}

【问题讨论】:

  • 我修复了 NULL bu 的问题,现在我在最后一行 current1 -> next = curren2 -> next 遇到了错误
  • 我编辑了我的答案以向您解释现在收到此错误。

标签: c list linked-list fault


【解决方案1】:

您确保current1 至少有一个元素与您的测试current1 != NULL 所以current1->next 保证工作,但它可能会返回NULL 本身导致current1->next->data 在尝试获取时崩溃next 元素中的数据。

【讨论】:

    【解决方案2】:

    在这一行你不知道current1->next 是否为NULL。如果它是NULL,并且您尝试访问current1->next->data,您将以segmentation fault 结尾。

    你有两种解决方案来修复你的循环:

    while(current1 != NULL && (current1->data != d))
        //                             ^^^^^^^
        current1 = current1 -> next; 
    

    或者

    if ( current1 != NULL )
        while (current1->next != NULL && (current1->next->data != d))
            //         ^^^^^^
            current1 = current1 -> next; 
    

    但在第二种情况下,您必须确保在第一个循环中current1 != NULL

    回复评论:

    同样的错误,你不知道current1是不是NULL,你尝试访问next元素,你有两件事要做:

    • 首先您必须确定current1 不是NULL,然后再尝试访问next
    • 在您必须确定 current2 也不是 NULL 之后。

    你有两种可能(很容易做到):

    if ( NULL != current1 )
    {
        current2 = current1->next;
    
        if ( NULL != current2 )
            current1->next = current2->next;
    }
    

    或者

    if ( NULL != current1 && NULL != current1->next )
    {
        current2 = current1->next;
        current1->next = current2->next;
    }
    

    两者都可以正常工作。选择您喜欢的。

    【讨论】:

      【解决方案3】:

      在您告诉我们有错误的那一行中,您永远不会检查 current1->next 是否为 NULL。在您的程序中的某个时刻,current1->next NULL,因此您正试图取消引用地址0。此时,代码相当于((struct list *)0)->data。因此分段错误。

      【讨论】:

        猜你喜欢
        • 2017-03-21
        • 2023-03-21
        • 2016-09-17
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多