我不明白为什么会出现“Segmentation fault (core dumped)”...它发生在我在 push 函数中调用 push 函数时。
node* push(node* head, node*cur, int n)
{
if(head==NULL)
{
head=(node*)malloc(sizeof(node));
ins(n, head);
head->next=NULL;
}
else
{
cur->next=(node*)malloc(sizeof(node)); //because initially head and cur are same!
cur=cur->next;
ins(n, cur);
cur->next=NULL;
}
printf("\nPress 1 to continue insertion: ");
int ch;
scanf("%d", &ch);
if(ch==1)
{
printf("\nEnter Digit to push: ");
int dig;
scanf("%d", &dig);
push(head, cur, dig);
}
return head;
}
void disp(node* head)
{
node* cur=head;
printf("printing::: %d and %d and %p and %p\n", head->dat, cur->next->dat, head, cur);
while(cur!=NULL)
{
printf("=>");
cur=cur->next;
}
}
最佳答案
问题好像是行
cur->next=(node*)malloc(sizeof(node));
因为正如您所说的 cur 与 head 相同,所以 cur 为 NULL 并且访问 next 为 NULL 是无效的。
要解决这个问题
if(head==NULL)
{
head=(node*)malloc(sizeof(node));
ins(n, head);
head->next=NULL;
cur=head; // <--change here
}
这样下一次 cur 将指向 head 并且您可以访问 cur 的 next。
关于c - 为什么会出现Segmentation Core dumped?我做了很多次链接列表,但不明白为什么这段代码中有一个转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971040/