在双链表中删除和添加节点时出现分段错误

时间:2013-06-09 14:24:07

标签: c doubly-linked-list

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

//double linked list
struct node {
    int data;
    struct node *rnext;
    struct node *lnext;
}*first=NULL,*last=NULL;
//double linked list

void insertion() {
    struct node *nn=malloc(sizeof(*nn));
    printf("enter data to be inserted\n");
    scanf("%d",&nn->data);
    nn->rnext=NULL;
    nn->lnext=last;
    if(first == NULL) {
        first = nn;
        last = nn;
    }
    else{
        last->rnext=nn;
    } 
    last=nn;
}

void display() {
    struct node *temp;
    if(first==NULL) {
        printf("list is empty\n");
        return;
    }
    temp=first;
    while(temp!=NULL) {
        printf("%d \n",temp->data);
        temp=temp->rnext;
    }
}

void deletion() {
    struct  node  *temp;
    if(first==NULL) {
        printf("list is empty\n");
        return;
    }
    temp=first;
    first=first->rnext;
    first->lnext=NULL;
    free(temp);
}

int main() {
    int  option;
    do {
        printf("enter option 1.insert\n  2.display\n  3.delete\n  4.exit\n");
        scanf("%d",&option);
        switch(option) {
        case 1:
            insertion();
            break;
        case 2:
            display();
            break;
        case 3:
            deletion();
            break;
        }
    } while(option!=4);
}

这是为在双链表中删除和插入节点而编写的程序。程序编译时没有错误,但是当在列表中只有一个节点时删除节点时,它在运行时失败并出现分段错误错误。任何人都可以帮助解决此分段错误的解决方案吗?

以下是该程序的一些示例输出:

./out
enter option 1.insertion
  2.display
  3.deletion
  4.exit
1
enter data to be inserted
11
enter option 1.insertion
  2.display
  3.deletion
  4.exit
2
11 
enter option 1.insertion
  2.display
  3.deletion
  4.exit
3
Segmentation fault

3 个答案:

答案 0 :(得分:0)

解决这个问题的绝对最简单的方法是在调试器中运行它。您可能甚至不需要学习如何单步执行代码或任何操作 - 只需启动,运行和读取该行。

如果你的标签显示在* nix上:

  1. 使用-g标记编译代码。
  2. 加载为,例如gdb a.out
  3. 现在运行它已加载 - (gdb) run
  4. 做任何你需要的东西来重现段错误。
  5. bt或者应该在哪里为您提供堆栈跟踪 - 以及导致您出现问题的确切行。
  6. 我确信你可以从那里解决这个问题作为答案;但如果没有,了解确切的线条将使研究和解决变得更加容易。

答案 1 :(得分:0)

至少有两个错误:

一方面,在插入功能中,内存分配不正确:

struct node *nn=malloc(sizeof(*nn));

应该是:

struct node *nn= (struct node *) malloc(sizeof(struct node));

另一方面,在删除功能中。如果只有一个节点。声明后

first=first->rnext;

指针首先变为NULL。然后你尝试将其用作:

first->lnext=NULL;  // first is NULL

然后分段失败。

答案 2 :(得分:0)

temp=first;
first=first->rnext;//when only one, first is NULL(first->rnext)
first->lnext=NULL;//(NULL)->lnext , Segmentation fault!!
free(temp);

也许修复

temp=first;
if(first == last){//if only one
    first = last = NULL;
} else {
    first=first->rnext;
    first->lnext=NULL;
}
free(temp);