[英]strlen and malloc: C memory leaks
这个问题是无效的! 我没有适当地释放学生! 我将尽快接受向我透露这一问题的答案!
我是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)));
线。
我是否有一些基本滥用滥用行为而导致错误?
这里有一些问题:
newStudentp -> last_name = (malloc(strlen(last_name)));
newStudentp -> first_name = (malloc(strlen(first_name)));
strlen
仅给出长度,但不包括终止符'\\0'
。 但这也必须存储,因此在两种情况下都应使用strlen(last_name) + 1
。
另外,最好使用分配的缓冲区的大小而不是源字符串的大小来完成strncpy()
,这样您就可以避免写入超出数组上限的情况。 但是由于您已经使用了malloc(strlen(...) + 1)
,因此可以在此处简单地使用strcpy()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.