如何正确释放与 getline() 函数相关的内存?
How do I properly free memory related to getline() function?
我刚开始编程,有一个初学者的问题,我想写一个函数来逐行读取一个未知长度的文件。因为我不知道每行的长度所以我使用了 getline()
函数:
void readDict(FILE *dict_file){
//Read dic
char *line;
size_t len = 0, read;
while((read = getline(&line, &len, dict_file))!=-1){
check(line);
}
free(line);
return;
}
因为 getline()
有点类似于 malloc()
和 realloc()
一个字符串,所以如果我继续使用这个函数来读取很多长度未知的行,我会得到内存泄漏或内存不足?
首先,您应该将lineptr
初始化为NULL
。如果没有正确的初始化,lineptr
将包含不确定的值,这使得 lineptr
指向无效的内存位置,稍后在处理过程中,它将在尝试分配时调用 undefined behavior (realloc()
) 适当的内存量。
然后,根据 man page,
[...] before calling getline()
, *lineptr
can contain a pointer to a malloc()
-allocated buffer *n
bytes in size. If the buffer is not large enough to hold the line, getline()
resizes it with realloc()
, updating *lineptr
and *n
as necessary.
所以,只要你通过相同的*lineptr
,如果你最后只free()
一次就可以了。
我刚开始编程,有一个初学者的问题,我想写一个函数来逐行读取一个未知长度的文件。因为我不知道每行的长度所以我使用了 getline()
函数:
void readDict(FILE *dict_file){
//Read dic
char *line;
size_t len = 0, read;
while((read = getline(&line, &len, dict_file))!=-1){
check(line);
}
free(line);
return;
}
因为 getline()
有点类似于 malloc()
和 realloc()
一个字符串,所以如果我继续使用这个函数来读取很多长度未知的行,我会得到内存泄漏或内存不足?
首先,您应该将lineptr
初始化为NULL
。如果没有正确的初始化,lineptr
将包含不确定的值,这使得 lineptr
指向无效的内存位置,稍后在处理过程中,它将在尝试分配时调用 undefined behavior (realloc()
) 适当的内存量。
然后,根据 man page,
[...] before calling
getline()
,*lineptr
can contain a pointer to amalloc()
-allocated buffer*n
bytes in size. If the buffer is not large enough to hold the line,getline()
resizes it withrealloc()
, updating*lineptr
and*n
as necessary.
所以,只要你通过相同的*lineptr
,如果你最后只free()
一次就可以了。