【发布时间】:2018-08-10 07:20:47
【问题描述】:
对于我的程序,我必须从一个空链表开始,并且能够对其执行各种操作(即添加到开头、添加到结尾等) 我的列表结构如下
struct node {
int num;
struct node *next;
};
这是我分配空间并初始化列表的函数的开头,然后是一个 while 循环,其中 case 1 是添加到开头的函数。 else部分可以忽略这个问题。
printf("Who's ready to create and edit a linked list?\n");
printf("Note: The list is currently empty, please choose option 1.\n");
int choice, val, location, created;
struct node *llist;
llist = (struct node*)malloc(sizeof(struct node));
created =0;
while(choice != 8)
{
printf(" Operation Choices\n");
printf("1. Insert node at beginning\n");
printf("2. Insert node at end\n");
printf("3. Delete node from end\n");
printf("4. Delete node from beginning\n");
printf("5. Delete node from custom position\n");
printf("6. Insert node at custom position\n");
printf("7. Modify custom node\n");
printf("8. Exit\n");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Value to enter: \n");
scanf("%d", val);
if(created == 0)
{
llist->num=val;
llist->next = NULL;
created = 1;
}
else
{
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp = llist;
free(llist);
llist = (struct node*)malloc(sizeof(struct node));
llist->num=val;
llist->next=temp;
free(temp);
showlist(llist);
}
break;
}
}
}
Choice 当前为“0”,这表示我没有向列表中添加任何值,并且 if 部分正在执行。当我运行代码并尝试添加我的第一个值时,即使分配了内存,我仍然会遇到分段错误。我错过了什么??
知道为什么这个打印功能也不起作用吗?
void showlist(struct node *list)
{
do{
printf("%d->", list->num);
list = list->next;
}
while(list->next != NULL);
}
【问题讨论】:
-
temp = llist; free(llist);为什么? -
Temp 包含整个列表,所以我想我应该释放内存来创建新的第一个节点。如果没有 free(llist),它仍然会产生分段错误。
-
@ebagl temp 不包含整个列表,temp 包含列表中第一个节点的地址。然后
free(llist)释放列表中的第一个节点。 -
temp = (struct node*)malloc(sizeof(struct node)); temp = llist;这是内存泄漏。您将malloc空间用于temp,然后将temp重新分配给不同的值而不保存其原始值。这段记忆现在悬而未决,没有任何引用。 -
那么不应该为'temp'分配内存吗?我也试过了,但没有成功。
标签: c linked-list segmentation-fault