【问题标题】:Why my program is crashing everytime when I run it? [closed]为什么我的程序每次运行时都会崩溃? [关闭]
【发布时间】:2016-05-09 13:40:19
【问题描述】:

我正在尝试学习链接列表中的插入技术。在执行期间,每次说程序停止工作时它都会崩溃。它没有显示任何错误。我是 Stack Overflow 的新手。如果这个问题已经被问过,请原谅我。这是我的代码:

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

    struct node{
    int data;
    struct node *next;
    };

    void push(struct node** head_ref, int new_data)
    {
     struct node* new_node= (struct node*)malloc(sizeof(struct node));
     new_node->data=new_data;
     new_node->next=(*head_ref);
     (*head_ref)=new_node;
    }
    void insertAfter(struct node* prev_node, int new_data)
    {
    if(prev_node==NULL)
    {printf("The previous node cannot be NULL");
        return;
    }
    struct node* new_node=(struct node*)malloc(sizeof(struct node));
    new_node->data=new_data;
    new_node->next=prev_node->next;
    prev_node->next=new_node;

    }

    void append(struct node** head_ref, int new_data)
    {
    struct node* new_node= (struct node*)malloc(sizeof(struct node));
    struct node *last= *head_ref;
    new_node->data=new_data;
    new_node->next=NULL;
    if(*head_ref==NULL)
    {
        *head_ref=new_node;
    }
    else
        while(last->next!=NULL)
    {
        last=last->next;  /* Segmentation fault */
    }
    last->next=new_node;
    return;
    }

      void printlist(struct node *node)
    {
      while(node!=NULL)
    {
        printf("%d",node->data);
        node=node->next;
    }

    }
    int main()
    {
    struct node* head=NULL;
    append(&head,6);
    push(&head,7);
    push(&head,11);
    append(&head,4);
insertAfter(head->next,12);
printf("\n Created Linked list is:");
printlist(head);
    return 0;
    }

【问题讨论】:

  • 使用调试器,先缩小有问题的指令范围。
  • 好吧,现在它说的是分段错误。你如何解决这个问题? (对不起,我还是编程新手)
  • 您的代码的某些格式也不会出错。
  • 我们需要知道错误发生在哪里...
  • 请注意(struct node*)malloc(sizeof(struct node)); 强制转换是不必要的,并且可能会掩盖类型错误。

标签: c data-structures linked-list insertion


【解决方案1】:

您检查头部为NULL 的情况,但else 子句仅包含while 循环。对last 的赋值在这两种情况下都会执行。

您应该在else 子句周围放置大括号:

    void append(struct node **head_ref, int new_data)
    {
        struct node *new_node = (struct node *) malloc(sizeof(struct node));
        struct node *last = *head_ref;

        new_node->data = new_data;
        new_node->next = NULL;

        if (*head_ref == NULL) {
            *head_ref = new_node;
        } else {
            while (last->next != NULL) {
                last = last->next;
            }
            last->next = new_node;
        }
    }

适当的缩进会使此类错误脱颖而出。在我看来,在整个过程中使用大括号也是一个好主意,也许除了非常短的ifs 在内循环中没有else

【讨论】:

  • 正确缩进并使用大括号 FTW。 (并且一些空白从未杀死任何人)
【解决方案2】:

至少,您正在尝试取消引用 NULL 指针(在 append 中)。

您可能想要if (head_ref==NULL) 而不是if (*head_ref==NULL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 2020-04-18
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2013-11-22
    相关资源
    最近更新 更多