簡體   English   中英

釋放鏈表的 memory 時出現 valgrind 錯誤

[英]valgrind error in freeing memory of a linked list

我開始熟悉鏈表和動態 memory。

#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 個字節肯定丟失在 loss record 1 of 1

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

通過 0x1086EB: 主要 (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本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM