【发布时间】: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