[英]How can I find the memory leak?
我正在构建一个 function,它读取一个文本文件并在每次调用 function 时返回一行。 output 似乎是正确的。 但是,我不断收到 memory 泄漏,无论我做什么,我似乎都无法修复它。
我有以下代码。
BUFFERSIZE = 10;
char *modify(char buffer[], char *line)
{
const int size = ft_strclen(line, '\n') + 1;
const int total = strlen(line) - size;
int i;
char *return_line;
i = 0;
return_line = malloc(sizeof(char) * ft_strclen(line, '\n') + 2);
if (!return_line)
return (NULL);
while (i < size && line[i])
{
return_line[i] = line[i];
i++;
}
return_line[i] = '\0';
i = 0;
while (i < total && line[size + i])
{
buffer[i] = line[size + i];
i++;
}
buffer[i] = '\0';
free(line);
return (return_line);
}
char *join_buffers(char *buf1, char *buf2)
{
const int length = strlen(buf1) + strlen(buf2);
char *new;
int i = 0;
int k = 0;
new = NULL;
new = malloc(sizeof(char) * (length + 1));
if (!new)
return (NULL);
while (i < length && buf1[i])
{
new[i] = buf1[i];
i++;
}
new[length] = '\0';
while(i < length && buf2[k])
new[i++] = buf2[k++]; // Not sure about this
new[i] = '\0';
return (new);
}
char *read_file(char *buffer, int fd)
{
int bytes_read;
char buff_read[BUFFER_SIZE + 1];
bytes_read = -1;
while (!search_char(buffer, '\n'))
{
bytes_read = read(fd, buff_read, BUFFER_SIZE);
if (bytes_read == -1)
return (NULL);
if (bytes_read == 0)
break ;
buff_read[bytes_read] = '\0';
buffer = join_buffers(buffer, buff_read);
}
return (buffer);
}
char *get_next_line(int fd)
{
static char buffer[BUFFER_SIZE + 1];
char *line;
line = NULL;
if (fd < 0 || BUFFER_SIZE <= 0 || read(fd, 0, 0) < 0)
return (NULL);
buffer[BUFFER_SIZE] = '\0';
line = read_file(buffer, fd);
if (line[0] == '\0' && buffer[0] == '\0')
return (NULL);
line = modify(buffer, line);
return (line);
}
我在想我必须在修改 function 中释放行。这修复了一些泄漏但不是全部。
modify() 中没有 free 的泄漏:9(256 字节)[...]
免费泄漏:5(128 字节)[...]
我隐藏了指针地址。
我忘记释放什么或者是其他地方的问题? 谢谢你。
这个说法:
line = NULL;
free(line);
改变了原来指向的line
,现在指向NULL
。 您现在已经失去了对原始 memory 的访问权限,并且无法在这个 function 中free
它,并且由于您没有在调用 function 中free
memory,因此导致泄漏。
在旁边:
free (NULL);
不执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.