【问题标题】:Removing node from doubly linked list gives segmentation fault - C从双向链表中删除节点会导致分段错误 - C
【发布时间】:2020-10-21 00:28:05
【问题描述】:

我编写了一个程序,可以将 char 字符添加到双向链表的开头。现在,一旦我有了这个列表,我的程序的目的就是从列表中完全删除某些 char 字符。例如(仅出于代表性目的使用大括号):如果列表由 { a, b, b, a, c } 组成,那么我的程序可以从列表中删除所有“b”以使其成为{ a, a, c}。此外,如果我的列表是 {b, a, c, a}{a, c, a, b} 并且如果我想删除“b”,那么程序在这两种情况下都可以正常工作并给我 {a, c, a}

但是有很多问题(对于所有情况,假设我想删除“b”):

  1. 如果我的列表是 {b, a, b, a, c}(“b”在前面,中间某处),我会遇到分段错误(我认为这与使用光标在while循环中,但我不知道究竟是为什么以及如何修复它)
  2. 如果我的列表是 {a, b, b, a, c, b}(中间最后是“b”),那么输出会给我奇怪的符号(我假设它是内存故障,不知道为什么)

这是我正在使用的代码:

#include<stdio.h>
#include<stdlib.h>

struct list
{
   int data;
   struct list* next;
   struct list* prev;
};

struct list* head; // global variable - pointer to head node of list.
struct list* last; // global variable - pointer to last node of list

//Creates a new list and returns pointer to it.
struct list* GetNewNode(char x)
{
   struct list* newNode
       = malloc(sizeof(struct list));
   newNode->data = x;
   newNode->prev = NULL;
   newNode->next = NULL;
   return newNode;
}

//Inserts a list at head of doubly linked list
void InsertAtHead(char x)
{
   struct list* newNode = GetNewNode(x);
   if(head == NULL)
   {
       head = newNode;
       return;
   }

   head->prev = newNode;
   newNode->next = head;
   head = newNode;
   struct list* temp = head;

   while (temp->next != NULL) temp = temp->next;
   last = temp;
}

void remove_element (char character)
{
   struct list * cursor, *previous, *store_el;
   //int boolean = 0;

   if (head == NULL) return;
   else
   {
       cursor = head;
       while(cursor != NULL)
       {
           if (cursor->data == character)
           {
               if (cursor->prev == NULL)
               {
                  // printf("deleting from front\n");
                   previous = head;
                   head = head->next;
                   head->prev = NULL;
                   //boolean = 1;
                   //free(previous);
               }
               if (cursor->next == NULL)
               {
                   //printf("deleting from back\n");
                   previous = last;
                   last = last->prev;
                   last->next = NULL;
                   //boolean = 1;
                   //free(previous);
               }
               else
               {
                  // printf("deleting from middle\n");
                   previous = cursor;
                   cursor = cursor->next;
                   cursor->prev = previous->prev;
                   store_el = previous->prev;
                   store_el->next = cursor;
                   cursor = head;

               }
               free(previous);
               //printf("head data = %c\n", cursor->data);
           }
           cursor = cursor->next;
       }
   }
}

//Prints all the elements in linked list in forward traversal order
void Print()
{
   struct list* temp = head;
   printf("Forward: ");
   while(temp != NULL)
   {
       printf("%c ",temp->data);
       temp = temp->next;
   }
   printf("\n");
}

int main()
{

   char character;
   /*Driver code to test the implementation*/
   head = NULL; // empty list. set head as NULL.

   // Calling an Insert and printing list before and after deletion of character
   InsertAtHead('c');
   InsertAtHead('a');
   InsertAtHead('b');
   InsertAtHead('b');
   InsertAtHead('a');
   Print();
   printf("After deletion:\n");
   remove_element ('b');
   Print();
}

【问题讨论】:

  • 7-8 小时是一个很长的时间来寻找这样的问题而没有找到任何东西。你究竟是如何接近它的?你只是在猜测吗?还是您使用的是调试器?
  • 我立即注意到的一件事是,当您删除头部的元素时,您的 cursor 不会被修改。您将替换磁头,释放旧磁头(存储在cursorprevious 中),然后继续使用带有cursor = cursor-&gt;next 的无效指针。您可以通过删除尾部的项目来执行类似的操作。当您删除一个元素时,您应该跟随next 指针前进光标。相反,您已经知道更改链接时接下来会发生什么(正如您在列表中间删除时明确处理的那样),因此您只需要更新它。
  • 我打错了,我现在已经正确编辑了我的帖子。我的意思是说我花了 7-8 个小时试图完成代码,但仍然花了 3 个小时左右才找到问题,没有任何运气。我用笔和纸尝试可视化双向链表并熟悉数据结构(我已经浏览了 15 页或其他内容)。我一直在尝试不同的方法来解决问题,但没有任何运气。不幸的是,我不知道如何使用调试器,也许您可​​以将我链接到教如何使用调试器的好资源。谢谢!
  • 您是否阅读了我对实际问题的评论? (或至少一个问题)
  • 是的,我阅读了您的评论,这是有道理的。不幸的是,我住的地方太晚了,所以我需要签字。非常感谢您的评论,我将在明天晚些时候尝试实施解决方案,并在此处报告。

标签: c doubly-linked-list


【解决方案1】:
/* 
*I changed the name of your variable 'last' to 'tail'
*I removed the code at the end of your InsertAtHead function
*I added "tail = newNode;"
*I changed the name of your variable 'previous' to 'garbage'
*I removed your variable 'store_el' completely.
*I could have changed the whole code in your remove element function because the 3 cases are unnecessary but anyway.
*/
//Inserts a list at head of doubly linked list
void InsertAtHead(char x){
    struct list* newNode = GetNewNode(x);

    if (head == NULL){
        head = newNode;
        tail = newNode;
        return;
    }

    head->prev = newNode;
    newNode->next = head;
    head = newNode;
}

void remove_element (char character){
    struct list * cursor,  *garbage;

    cursor = head;
    while(cursor != NULL){
        if (cursor->data == character){
                garbage = cursor;

                if (cursor->prev == NULL){
                    head = head->next;
                    If (head!=NULL) head->prev = NULL;
                    cursor=head;
                }else if (cursor->next == NULL){
                    tail = tail->prev;
                    tail->next = NULL;
                    cursor=NULL;
                }else{
                    garbage->prev->next = garbage->next;
                    garbage->next->prev = garbage->prev;
                    cursor=cursor->next;
                }

                free(garbage);
        } else cursor=cursor->next;
    }
}

现在就试试吧。

你的代码的问题是你使用了你释放的内存。

/*
*cursor and previous point to the same memory address
*you free the memory that the variable previous points so the cursor points to that freed memory 
*when you save the next address to the cursor using that freed memory you create an undefined behaviour (your code may work or may not)
*/
cursor = head;
        while(cursor != NULL)
        {
            if (cursor->data == character)
            {
                if (cursor->prev == NULL)
                {
                    previous = head;
                    head = head->next;
                    head->prev = NULL;
                    free(previous);
...
cursor=cursor->next;

改进的代码:

#include<stdio.h>
#include<stdlib.h>

//The type of your variable data was wrong. I changed it to char
struct list{
    char data;
    struct list *prev, *next
};

void remove_element (char character){
    struct list * cursor,  *garbage;

    cursor = head;
    while(cursor != NULL){
        if (cursor->data == character){
                garbage = cursor;

                if (garbage->prev!=NULL ) garbage->prev->next = garbage->next;
                if (garbage->next!=NULL ) garbage->next->prev = garbage->prev;
                cursor=cursor->next;

                if (head==garbage) head=cursor;
                //Basically the tail variable has no use for your current program.
                //if (tail==garbage) tail=garbage->prev;

                free(garbage);
        } else cursor=cursor->next;
    }
}

【讨论】:

  • 谢谢你,这似乎很有效,也很有意义!但我想知道如何更改我的代码,以便根本不需要“remove_element”函数中的 3 个案例,但我的程序也可以按预期工作。你对此有什么建议吗?
【解决方案2】:

尝试更新光标

cursor = head;

从前面删除后。

【讨论】:

    【解决方案3】:

    Ellothere 我认为你的程序中的问题是你在之前分配了节点的地址,但你没有并排释放它。

           if (cursor->prev == NULL)
           {
              // printf("deleting from front\n");
               previous = head;
               head = head->next;
               head->prev = NULL;
               //boolean = 1;
               //free(previous);
           }
           if (cursor->next == NULL)
           {
               //printf("deleting from back\n");
               previous = last;
               last = last->prev;
               last->next = NULL;
               //boolean = 1;
               //free(previous);
           }
    

    你在这里存储节点,但在最后释放它,然后这里有 2 个 if 语句然后发生的事情是 {a b b a c} 中的两个 'b' 彼此相邻,所以首先 previous variable 存储第一个 'b' 的地址,然后存储 next 'b' 的地址,它只是释放那个 'b' 和那个 'b'仍然在那里。简而言之,您应该并排释放节点。我做了这个小改动,效果很好。

    if (cursor->prev == NULL)
                   {
                      // printf("deleting from front\n");
                       previous = head;
                       head = head->next;
                       head->prev = NULL;
                       free(previous);
                       //boolean = 1;
                       //free(previous);
                   }
                   if (cursor->next == NULL)
                   {
                       //printf("deleting from back\n");
                       previous = last;
                       last = last->prev;
                       last->next = NULL;
                       free(previous);
                       //boolean = 1;
                       //free(previous);
                   }
                   else
                   {
                      // printf("deleting from middle\n");
                       previous = cursor;
                       cursor = cursor->next;
                       cursor->prev = previous->prev;
                       store_el = previous->prev;
                       store_el->next = cursor;
                       cursor = head;
    
                   }
    

    我刚刚在两个 if 语句中添加了一个 free 函数。

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2013-09-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2011-03-12
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多