这个问题是无效的!我没有正确地释放学生!我会尽快接受向我透露这一点的答案!
我是 C 新手,正在练习 malloc。从宏观上讲,我正在编写一个链表库;这个 create_student 函数是我将用来测试我的链表库的许多函数之一。问题是...我运行 valgrind 并调用此函数,它表明第一个 malloc 导致了多个内存泄漏。据我所知,这一切看起来都很可靠:
typedef struct Student
{
char* first_name; /* This will be malloc'd!*/
char* last_name; /* This will also be malloc'd */
int grade;
long id;
} Student;
Student* create_student(const char* first_name, const char* last_name, int grade, long gtid)
{
/* First allocate a student on the heap */
Student *newStudentp = (malloc(sizeof(Student)));
/* Allocate enough space for the first and last names */
newStudentp -> last_name = (malloc(strlen(last_name)));
newStudentp -> first_name = (malloc(strlen(first_name)));
// AND copy the first and last name to the first and last name fields in the struct
strncpy(newStudentp -> first_name, first_name, strlen(first_name));
strncpy(newStudentp -> last_name, last_name, strlen(last_name));
/* Set the grade and id */
newStudentp -> grade = grade;
newStudentp -> id = id;
*/
return newStudentp;
}
我来自 valgrind 的错误消息(有几个)如下所示:
==4285== 9 bytes in 1 blocks are definitely lost in loss record 8 of 8
==4285== at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==4285== by 0x804855B: create_student (test.c:24)
==4285== by 0x8048748: main (test.c:109)
第 24 行是
newStudentp -> last_name = (malloc(strlen(last_name)));
line.
我是否对 strlen 有一些根本性的误用导致了错误?