释放链表的内存时出现valgrind错误

问题描述

我让自己熟悉链接列表和动态内存。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
    char *name;  // name of student
    char ID[7];  // student ID (nul terminated)
    // you may add fields to this structure if needed
} Student;

typedef struct Course_st {
    // add fields here
    Student *Student_list;
    struct Course * next;
} Course;


// kirjoita ohjelma tähän

int main()
{
    Course *course_1 = (Course*)malloc(1*sizeof(Course));

    Student *st_1 =malloc(sizeof(Student));
    st_1->name = malloc(5*sizeof(char));
    strcpy(st_1->name,"Hien");
    strcpy(st_1->ID,"001");

    course_1->Student_list = st_1;
    course_1->next = malloc(sizeof(Course));

    Student *st_2 = malloc(4*sizeof(Student));
    st_2->name = malloc(4*sizeof(char));
    strcpy(st_2->name,"Kim");
    strcpy(st_2->ID,"002");
    
    Course* next = (Course*) course_1->next;
    next->Student_list = st_2;
    next->next= NULL;

    while(course_1 != NULL)
    {
        printf("%s %s\n",course_1->Student_list->name,course_1->Student_list->ID);
        free(course_1->Student_list->name);
        free(course_1->Student_list);
        course_1 = (Course*)course_1->next;
    }
    free(next);
}

我又得到了这个错误...

在退出时使用:1个块中的16个字节

总堆使用情况:7个分配,6个空闲,4,217个字节分配

1个块中的16个字节肯定在1的丢失记录中丢失

在0x4C2FB0F:malloc(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so中)

by 0x1086EB:main(teht3.c:21)

泄漏摘要:

绝对丢失:1个块中的16个字节

...

有关检测到和抑制的错误的计数,请重新运行:-v

错误摘要:来自1个上下文的1个错误(禁止显示:0至0)

解决方法

使用malloc(...)分配的所有内容也应该与free(...)一起释放。就您而言,您没有释放course_1。因此解决方案应该是:

Course * tmp = course_1;
Course * tmp_next;    

while(tmp != NULL)
{
    printf("%s %s\n",tmp->Student_list->name,tmp->Student_list->ID);
    free(tmp->Student_list->name);
    free(tmp->Student_list);
    tmp_next = tmp->next;
    free(tmp);
    tmp = tmp_next;
}
,

我会这样更改程序的结尾

        Course *old_course_1=course_1;
        course_1 = (Course*)course_1->next;
        free(old_course_1);
    }
    // free(next);

这样,您一考虑下一个就可以释放course_1;就这样 不需要最后一次致电free(next)

您正确释放了course_1的动态部分,但没有释放 course_1本身。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...