此問題無效!我沒有妥善解放學生!我會盡快接受向我透露這個答案的答案!strlen和malloc:C內存泄露
我是C新手,正在練習malloc。在宏觀範圍內,我在寫一個鏈表庫;這個create_student函數是我要用來測試我的鏈表庫的許多函數。問題是...我運行valgrind並調用這個函數,它表明有幾個內存泄漏是由第一個malloc引起的。這一切看起來堅實,最好就我所知:從Valgrind的
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;
}
我的錯誤信息(有幾個)是這樣的:
==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)));
線。
是否存在導致錯誤的一些基本的濫用strlen的問題?
你是如何免費學習結構的? – Mat
請注意,'strlen'返回字符串_not_的長度,包括終止的''\ 0''字符。 – Hasturkun
你的用於'last_name'的'malloc'應該分配'strlen(last_name)+ 1'字符以包含'\ 0'的空間(與'first_name'相同) – jonsca