指向结构的指针的 C 中的 Free() 函数未编译

Free() Function in C of pointer to struct not compiling

我已经实现了一个链表,我正在尝试创建一个函数,该函数从链表的头部开始,基本上将指向结构的指针存储在 curr 中。然后它使用 free()...不幸的是我不断得到

LinkedList_Header(27343,0x1000dedc0) malloc: *** error for object 0x1007b42c0: pointer being freed was not allocated

struct node {
    int data;
    struct node* next;
};

struct node* initialize(int input){
    struct node* head = (struct node*)malloc(sizeof(struct node));
    head->data = input;
    head->next = NULL;
    return head;
}

void freeing(struct node* head){
    struct node* curr = head;
    while(curr->next != NULL){
        free(curr);
    }
    free(curr);
}

您的代码的问题是 freeing 函数不正确。函数失败有两种可能的方式。

双倍免费

  1. 如果链表的headnext指针上有一个有效的指针,释放函数会一直循环到同一个初始指针,也就是头。这将创建一个双重释放,因此您释放了一个未分配的指针。
//Would loop forever if it wasn't because of the double free.
//The loop never continues into the next pointer, and stays on the head.
struct node* curr = head;
while(curr->next != NULL){
     free(curr);
}

从不通过链表积分

  1. 你的代码的第二个问题是 while 循环总是在头部迭代,如果不是因为 double free,循环将永远迭代。

问题1和问题2的解决方案是让while循环正确地遍历链表。

void freeing(struct node* head){
    struct node* curr = head;
    struct node* next;
    while(curr != NULL){
        next = curr->next;
        free(curr);
        curr = next;
    }
}

带测试的完整代码:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* next;
};

struct node* initialize(int input){
    struct node* head = (struct node*)malloc(sizeof(struct node));
    head->data = input;
    head->next = NULL;
    return head;
}

void freeing(struct node* head){
    struct node* curr = head;
    struct node* next;
    while(curr != NULL){
        next = curr->next;
        printf("Freeing: %d\n", curr->data);
        free(curr);
        curr = next;
    }
}

int main()
{
    struct node* a = initialize(23);
    a->next = initialize(42);
    freeing(a);
}

这是输出,现在代码避免了双重释放并正确迭代。

Freeing: 23
Freeing: 42