【问题标题】:Linked List Segmentation Fault C链表切分故障C
【发布时间】:2013-07-09 22:38:44
【问题描述】:

我正在学习 C 中的链表,但我的删除函数有问题,一直给我一个分段错误。我不知道代码有什么问题。

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; 
}

【问题讨论】:

  • 过去 30 分钟内,这个问题被问了两次。
  • 如果您使用 C++ 编译器(例如 Visual C++)编译此代码 - 请检查您的名为 delete 的函数是否存在问题。这是一个保留关键字
  • 看来current1这行NULL可能是current2 = current1 -> next;
  • 我以前在实验室里辅导人的时候,我会让他们在纸上画出他们的链表,然后想象他们的代码在上面运行。这个简单的技巧为他们省去了很多麻烦。
  • 粗略一看,我有点怀疑尾部节点上的 'while (current1->next->next != NULL)' 可能会发生什么。

标签: c linked-list segmentation-fault


【解决方案1】:

这在很多方面都是错误的:

1)

while (current1->next->next != NULL)

如果列表只有一个元素:

current1 = head;
current1->next = NULL; 
current1->next->next = Seg Fault

2)
如果您要查看最后一个元素是否具有提供的数据,请确保在找到它后从函数中返回,并为其释放内存:

while(current1->next->next != NULL)
    current1 = current1->next;
if(current1->next->data == d){
        free(current->next);
        current1->next == NULL;
        return; 
}


3)
如果您在最后一个元素有您的数据的情况下进行上述搜索(尽管搜索毫无意义;无需单独进行),您可以从下面的代码中消除错误情况。但是当您的数据无法在列表中找到并且current1 位于最后一个元素(所以!= NULL)但current1->next->data != d 使您的程序崩溃时,您仍然会遇到这种情况。如果您不从 2) 处的函数返回,就会发生这种情况。

current1 = head; //move current1 back to front */
while(current1 != NULL && (current1->next->data != d))
    current1 = current1 -> next; 


4)
已删除节点的可用内存:

current2 = current1 -> next;
current1 -> next = current2 -> next; 
free(current2);

【讨论】:

    【解决方案2】:

    一瞥:

    假设有 100 个结构,范围从 1 到 99。
    第 100 个将 (可能)为 NULL。


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

    当上述代码到达第 99 个结构时。您执行 2 次检查。

    1) 检查第 99 位是否不为 NULL .. 返回 true
    2) 检查第 100 位数据是否与 d 不同

    但是没有第 100 个结构。
    这会导致未定义的行为,可能并且可能导致段错误。

    【讨论】:

    • 谢谢,但我仍然在 current1->next = current2->next; 处遇到错误;
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    相关资源
    最近更新 更多