【问题标题】:What is the reason for this segmentation fault in this Linked List program?这个链表程序中出现这种分段错误的原因是什么?
【发布时间】:2015-04-23 01:35:54
【问题描述】:

当我添加最后一个节点时,这个程序总是给我一个分段错误,这可能是什么原因。它仅在添加最后一个节点时出现,我已经评论了我得到分段错误的行。 我是编程新手。

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

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


struct node *createNode(int val){
        struct node *ret=(struct node *)malloc(sizeof(struct node));
        ret->data=val;
        ret->next=NULL;
        return ret;
}


struct node *addNode(struct node *ll,int val){
        //Gives error here for the last node, it creates the node succesfull but this step give segmentation fault
        struct node *new_node=createNode(val);
        new_node->next=ll;
        return new_node;
}

void printList(struct node *ll){
        printf("printing list");
        struct node *temp=ll;
        while(temp->next){
                printf("%d ->",temp->data);
                temp=temp->next;
        }
}

int main(){
        struct node *head;
        head=addNode(head,3);
        head=addNode(head,5);
        head=addNode(head,1);
        head=addNode(head,9);
        printList(head);
}

【问题讨论】:

  • 您是否尝试过通过调试器运行它?如果没有,请执行此操作并观察范围内所有变量的值,寻找任何可疑之处。
  • 我希望代码在这里崩溃:printList()

标签: c segmentation-fault singly-linked-list


【解决方案1】:

您正面临这个问题,因为当您在链接列表中添加新节点时,您将此节点添加为链接列表的开始。

最初:

struct node* head; //This is not NULL.Big mistake by you.But this is not the only problem.

存在分段错误,因为您试图访问 printList() 中的无效内存位置,因为最后一个节点指针(最初由您声明为 head)未指向任何有效的内存位置。尝试评论对printList() 的调用,您会看到该错误。但这不是您正在寻找的解决方案,即使您将头部初始化为NULL,您也会面临最后一个节点不会被打印的问题。为此使用:-

while(temp)

printList().

【讨论】:

    【解决方案2】:

    NULL 分配给头部。

     struct node * head=NULL;
    

    因为在 addnode 中你是这样做的,

     new_node->next=ll;
    

    然后在打印节点的同时做出这样的条件,

    while(node){
    ...
    }
    

    如果您使用node&gt;next,您将丢失链表中的最后一个值。

    Don't cast malloc 和家族。

    【讨论】:

      【解决方案3】:
       struct node *head;
      

      head 未初始化,因此使用未初始化的变量会导致未定义的行为。在添加节点之前将head 初始化为NULL

       struct node *head = NULL;
      

      DO NOT CAST MALLOC AND FAMILY

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 2020-12-10
        • 1970-01-01
        • 2016-10-18
        • 2019-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多