該程序在第一個printf
語句後導致分段錯誤。 據我所知,在內存堆棧滿的情況下出現分段錯誤。但在我的情況下,沒有遞歸程序,只有在調用一個程序4次之後。鏈接列表程序中的分段錯誤
請幫我理解爲什麼會發生這種情況。
下面是代碼:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int data;
struct node *link;
};
void append(struct node **, int);
void addatbeg(struct node **,int);
int count(struct node *);
void display(struct node *);
void addafter(struct node **, int,int);
int main()
{
struct node *q;
q= NULL; //list is empty
append(&q,10);
append(&q,20);
append(&q,30);
append(&q,40);
printf("Now display the contents of the linked list:\n");
display(q);
addatbeg(&q,17);
addatbeg(&q,59);
printf("after adding the elements in the beginning, new linked list contents are\n");
display(q);
addafter(&q,4, 15);
addafter(&q,7, 25);
printf("after adding the elements at specified location, list elements are: \n");
display(q);
printf("\n\nCounting of list elements, list has %d elements", count(q));
return 0;
}
void append(struct node **p, int num)
{
struct node *temp, *r;
temp=*p;
if(*p==NULL)
//Linked list is empty and the node to be added is the first node
{
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
temp->link=NULL;
*p=temp;
}
else
{
while(temp->link!=NULL)
{
temp=temp->link;
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=NULL;
temp->link=r;
}
}
}
void addatbeg(struct node **p, int num)
{
struct node *temp, *r;
temp=*p;
r=(struct node *)malloc(sizeof(struct node));
r->data=num;
r->link=temp->link;
*p=r;
}
void addafter(struct node **p, int loc, int num)
{
int i;
struct node *temp, *r;
temp=*p;
//first we will find out the desired loc
for(i=0; i<loc; i++)
temp=temp->link;
//now need to create a new node
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=temp->link;
temp->link=r;
}
void display(struct node *p)
{
while(p!=NULL)
p=p->link;
printf("\n%d\t",p->data);
}
int count(struct node *p)
{
int count=0;
while(p!=NULL)
{
p=p->link;
count++;
}
return count;
}
並在下次發佈問題代碼時刪除行號。 – WhozCraig 2013-03-19 06:42:29