c - 编写一个函数来释放从链表创建的内存

标签 c malloc

我有以下定义链表节点的结构代码

struct list {
    struct student s;
    struct list *next;
};

我的学生结构定义如下

struct student{
    unsigned short year;
    unsigned short grade;
    unsigned char *details;
};

假设我的程序创建了一个学生链表,我想编写一个函数来释放我进行的每个 malloc 调用。

在我的程序中,每次初始化 *details 时,以及每次为列表创建节点时,我都会调用 malloc。

如果这有帮助,这是我创建节点的函数:

struct list *create_node(struct student *p) {
    struct list *node = malloc(sizeof(struct list));
    node->p = *p;
    node->next = NULL;
    return node;
}

我想写一个函数来释放所有用 malloc 来保存列表的内存。

这是我的尝试

void free_list(struct list *node){

    // free this first node
    free(node->p.details);
    while (node->next != NULL){
        // become the next node and free
        node = node->next;
        free(node->p.details);
    }

最佳答案

你的免费功能可以是这样的

void free_list(struct list *node){

struct list  *temp = NULL;

// free this first node
//free(node->p.details);
while (node != NULL){
    temp = node;
    // become the next node and free
    node = node->next;
    free(temp->p.details);
    temp->p.details = NULL;
free(temp);
}

关于c - 编写一个函数来释放从链表创建的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668369/

相关文章:

c - 获取指向字符串常量的指针

c - 如何检查嵌套结构的 malloc 结果?在C中

c - sizeof(char) 和 sizeof(char *) 的区别

c - 使用 malloc() 分配内存时出错,只能向表中添加一项

c - 为什么 ENOENT 表示 "No such file or directory"?

c - 将从数据库读取的数据值写入C程序中的变量: (Sqlite database is used with c interface)

c - 如何编译交叉编译器arm-linux-eabi-gcc?

C - 并发问题

C: Malloc 段错误

C - free() 没有释放整个数组