strlen 和 malloc:C 内存泄漏

2024-01-04

这个问题是无效的!我没有正确地释放学生!我会尽快接受向我透露这一点的答案!

我是 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 有一些根本性的误用导致了错误?


这里有几个问题:

    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() here.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

strlen 和 malloc:C 内存泄漏 的相关文章

随机推荐