【发布时间】:2017-04-09 19:42:24
【问题描述】:
C 的新手,在发布之前尝试了我发现的其他 SO Answers,发现他们都没有使用函数并通过引用传递他们的列表来删除所有项目,但这就是我想要的方式实施它。控制台正在输出
* `./testing' 中的错误:双重释放或损坏(输出):0x00007ffc26622b30 * 中止
对于一个菜鸟来说很棒的错误信息!这一点也不神秘。 :)
附言我的所有其他功能都按预期工作。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node
{
int n;
struct node* next;
}
node;
bool search(int number, node* list);
void showItems(node* list);
void insertItem(int number, node** list);
void deleteItem(int number, node** list);
void deleteList(node** list);
int main(void)
{
node* list = NULL;
insertItem(1337, &list);
insertItem(1337, &list);
bool found = search(5, list);
if (found)
{
printf("found number in linked list.");
}
deleteList(&list);
showItems(list);
}
void showItems(node* list)
{
node* ptr = list;
while (ptr)
{
printf("%i\n",ptr->n);
ptr = ptr->next;
}
}
bool search(int number, node* list)
{
node* ptr = list;
while (ptr)
{
if (ptr->n == number)
{
return true;
}
ptr = ptr->next;
}
//Number not found.
return false;
}
void insertItem(int number, node** list)
{
node* newItem = malloc(sizeof(node));
newItem->n = number;
newItem->next = *list;
*list = newItem;
}
void deleteItem(int number, node** list)
{
node* ptr = *list;
node* prev = NULL;
while (ptr)
{
if (ptr->n == number)
{
if (prev != NULL)
{
//Check if there is a previous node. If there is, set its next node to the current items next node. Then free the current node.
prev->next = ptr->next;
}
free(ptr);
break;
}
prev = ptr;
ptr = ptr->next;
}
}
void deleteList(node** list)
{
node* temp = NULL;
while (list)
{
temp = *list;
free(list);
list = &temp->next;
}
}
【问题讨论】:
-
1)
while (list):无限循环。 2)deleteList(&list); showItems(list);-->showItems(list); deleteList(&list); -
@BLUEPIXY 列表在每次迭代结束时被设置为 &temp->next,最终 temp->next 将 == NULL,从循环中中断....
-
temp->next将是== NULL,但&temp->next != NULL -
或
while(*list){ temp = *list; *list = temp->next; free(temp);}(可能是这种预期行为。) -
C 不支持引用,严格按值传递。
标签: c list linked-list