[英]Memory leak / not properly freeing. How to fix?
我正在将输入部分读入 function 中的缓冲区,然后在 main() 中释放它,但它似乎不起作用。 我的代码:
char *save_to_buff()
{
int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
const size_t read_size = 100; // set chunk size
size_t size = read_size;
char *buff = malloc(size+1);
size_t offset = 0;
size_t res = 0;
while((res = read(fd, buff + offset, read_size)) > 0) // partial read from stdin and save to buff
{
if(res == -1) // check for read errors
{
read_error();
free(buff);
return NULL;
}
offset += res;
if (offset + read_size > size)
{
size *= 2;
buff = realloc(buff, size+1);
}
buff[offset] = '\0';
}
return buff;
}
主要的:
char *buff = save_to_buff();
// do sth
free(buff);
编辑:刚刚尝试了 1 字节读取而不是部分读取,并且没有 memory 泄漏。
当您读取整个文件一次时,读取指针位于 EOF,如果您再次读取,就像在您的代码中一样, read()
将根据this返回 0。 这将退出您的循环而不释放 memory。
此外,取决于您正在阅读的文件类型:不支持查找的文件 - 例如终端 - 始终从当前 position 读取。 与此类文件关联的文件偏移量的值未定义
您没有发布main()
function 的完整代码,可能有一些我们看不到的可疑内容。
function save_to_buff
有一些问题:
stdin
在启动时已经位于文件末尾,它将返回一个指向未初始化的101
字节块的指针。 它应该返回 null 指针或指向空字符串的指针。只要您不修改// do sth
部分中的buff
,代码片段中的调用顺序似乎很好。
这是修改后的版本:
#include <stdio.h>
#include <unistd.h>
char *save_to_buff() {
int fd = 0; // set read() to read from STDIN_FILENO
const size_t read_size = 100; // set chunk size
size_t size = read_size;
size_t offset = 0;
size_t res = 0;
char *buff = malloc(size + 1);
if (buff == NULL)
return NULL;
*buff = '\0';
while ((res = read(fd, buff + offset, read_size)) != 0) {
// partial read from stdin and save to buff
if (res == (size_t)-1) { // check for read errors
read_error();
free(buff);
return NULL;
}
offset += res;
buff[offset] = '\0';
if (offset + read_size > size) {
char *buff0;
size *= 2;
buff = realloc(buff0 = buff, size + 1);
if (buff == NULL) {
free(buff0);
return NULL;
}
}
}
return buff;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.