【问题标题】:Memory leaks issue with malloc in CC 中 malloc 的内存泄漏问题
【发布时间】:2019-04-28 10:00:24
【问题描述】:

我对@9​​87654321@ 和malloc 比较陌生。我写了一个 lib ,其中包含一些基本功能,我正在使用新功能来填充这些功能,并且我正在将其用于像这样的其他小型项目。

我听说了 Valgrind 并决定用它检查我的程序,但不太明白为什么我有这么多 leaks,我觉得我所有的 mallocs 在使用使用 @987654327 的函数时都受到 if (line == NULL) 的保护@他们自己。

你们能让我回到这里吗?

static char *concator(char *s1, char *s2, size_t len)
{
    char    *line;
    size_t  size;

    if (!s1 || !s2)
        return (NULL);
    size = strlen(s1) + strlen(s2);
    line = (char*)memalloc(sizeof(char) * size + 1);
    if (line == NULL)
        return (NULL);
    strcpy(line, s1);
    strncat(line, s2, len);
    strdel(&s1);
    return (line);
}

int line_reader(const int fd, char **line)
{
    static char buf[BUFF_SIZE];
    char        *pos;
    int         ret;

    if (fd < 0 || !line || read(fd, buf, 0) < 0 || BUFF_SIZE < 1)
        return (-1);
    *line = strnew(0);
    if (line == NULL)
        return (-1);
    while (1)
    {
        pos = strchr(buf, '\n');
        if (pos)
        {
            *line = concator(*line, buf, pos - buf);
            if (line == NULL)
                return (-1);
            strncpy(buf, &buf[pos - buf + 1], BUFF_SIZE - (pos - buf));
            return (1);
        }
        *line = concator(*line, buf, BUFF_SIZE);
        if (line == NULL)
            return (-1);
        ret = read(fd, buf, BUFF_SIZE);
        buf[ret] = '\0';
        if (!ret)
            return ((**line) ? 1 : 0);
    }
}

【问题讨论】:

  • 您在代码中的哪个位置free正在分配您分配的内存?
  • Valgrind 可能告诉你的(包括它的报告在这里)是你没有在程序终止之前释放你分配的内存。
  • @ChrisTurner 我怎样才能free return 需要什么?
  • 你会在用完之后释放它,而不是在你归还它的时候。
  • 您没有使用 realloc 来扩展 *line 的大小 - 您一直在为其分配新的内存块并失去对旧内存的跟踪。

标签: c memory-leaks malloc


【解决方案1】:

使用完后免费line,例如:

char* line;
int rc = line_reader(fd, &line);
if(rc > 0)
{
    //use line
    printf("%s\n", line);
    //then free it
    free(line);
} 

这应该可以解决 valgrind 报告的内存泄漏问题。但是请注意 cmets 中提到的其他错误。

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2021-01-18
    • 2010-12-15
    相关资源
    最近更新 更多