我试图编写一个删除列表中某些节点的结构,删除功能正常工作,但我得到一个双重免费错误。
我无法弄清楚哪个免费给了我这个问题。我很感激任何帮助
struct dog* delete_from_list(struct dog *dogs)
{
int number2 = 0;
struct dog *temp, *cur = dogs;
if (dogs==NULL)
{
printf("There are no dogs on the list \n");
return 0;
}
printf("Enter patient number to delete: \n");
scanf("%d", &number2);
if (dogs->number==number2)
{
if(dogs->next==NULL) //only one node in the list
{
free(dogs);
return NULL;
}
dogs = dogs->next; //moves the head to next node
free(cur);
return dogs;
}
else
{
while (cur->next != NULL && cur->next->number != number2)
{
cur = cur->next;
}
if(cur->next==NULL)
{
printf("Dog with number %d is not present \n", number2);
return dogs;
}
temp = cur->next;
cur->next = cur->next->next;
free(temp);
return dogs;
}
}
答案 0 :(得分:0)
为避免双重误差,请尝试以下操作:
free
指针后右,将其设置为NULL free
指针前右,检查它是否为NULL 我会尝试删除特殊外壳的数量,例如
typedef struct dog Node;
Node * delete_from_list(Node * head) {
const int key_to_delete = GetKeyToDelete();
if (!head) return NULL;
for (Node * cur = head; cur; ) {
if (cur->key = key_to_delete) {
Node * curnext = cur->next;
free(cur);
cur = curnext;
}
else {
break;
}
}
Node * new_head = cur;
for (Node * cur = new_head; cur; cur = cur->next) {
if (cur->next && (cur->next->key == key_to_delete)) {
Node * curnextnext = cur->next->next;
free(cur->next);
cur->next = curnextnext;
}
}
return new_head;
}