【问题标题】:How can I find the memory leak?我怎样才能找到内存泄漏?
【发布时间】:2023-01-11 02:06:55
【问题描述】:

我正在构建一个读取文本文件并在每次调用该函数时返回一行的函数。输出似乎是正确的。但是,我一直遇到内存泄漏问题,无论我做什么,我似乎都无法修复它。

我有以下代码。

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';
    line = NULL;
    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);
}

我在想我必须在修改功能中释放行。这修复了一些泄漏,但不是全部。

modify() 中没有 free 的泄漏: 9(256 字节) [...]

免费泄漏: 5(128 字节) [...]

我隐藏了指针地址。

我忘记释放什么或者是其他地方的问题?谢谢你。

【问题讨论】:

  • line = NULL; free(line); 有什么意义?这是一个泄漏。

标签: c memory-leaks


【解决方案1】:

这个说法:

line = NULL;
free(line);

更改line 最初指向的内容,使其现在指向NULL。你现在已经失去了对原始内存的访问权,并且无​​法在这个函数中free它,并且因为你没有free调用函数中的内存,所以导致了泄漏。

在旁边:

free (NULL);

不执行任何操作。

【讨论】:

  • 旁白:指针的值是由调用者传递的,因此理论上调用者可以free它。
  • @Weather Vane 你是对的。我编辑了答案:)。
  • 呼叫者,召集者可以访问它:它是一个函数参数,是调用者变量的副本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
  • 2011-02-25
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多