【发布时间】:2020-12-04 17:18:27
【问题描述】:
我正在熟悉链表和动态内存。
#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个block中的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)
【问题讨论】:
-
程序在第 21 行分配了一些东西,但它从未释放它。
标签: c linked-list valgrind dynamic-memory-allocation