此链接列表程序中此分段错误的原因是什么?

时间:2015-02-21 10:40:48

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

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

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

3 个答案:

答案 0 :(得分:3)

 struct node *head;

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

 struct node *head = NULL;

DO NOT CAST MALLOC AND FAMILY

答案 1 :(得分:1)

NULL分配给头部。

 struct node * head=NULL;

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

 new_node->next=ll;

然后在打印节点时创建这样的条件,

while(node){
...
}

如果您使用node>next,则会丢失链接列表中的最后一个值。

Don't cast malloc和家庭。

答案 2 :(得分:0)

您遇到此问题,因为当您在链接列表中添加新节点时,您将此节点添加为链接列表的开头。

最初:

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()中的

相关问题