【问题标题】:Free() Function in C of pointer to struct not compiling指向结构的指针的 C 中的 Free() 函数未编译
【发布时间】:2021-02-08 01:32:06
【问题描述】:

我已经实现了一个链表,我正在尝试创建一个函数,该函数从链表的头部开始,本质上将指向该结构的指针存储在 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);
}

【问题讨论】:

  • 你的 curr 在循环内部总是相同的。你没有 next 循环
  • 将您的代码搁置几分钟,然后回来阅读您实际编写的内容,而不是您认为您编写的内容...
  • 在一个循环中,只要当前节点不为NULL,就保存当前节点的“next”指针,释放当前节点,然后使保存的“next”成为新的当前节点。
  • 您引用的错误似乎不是编译器错误。在“不编译”旁边,这让我感到困惑。

标签: c pointers free


【解决方案1】:

您的代码的问题是 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 循环将始终在头部迭代,如果不是因为双重释放,循环将永远迭代。

问题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

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2017-04-02
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2012-07-16
    • 1970-01-01
    相关资源
    最近更新 更多