c - C 中 malloc 的内存泄漏问题

标签 c memory-leaks malloc

我对Cmalloc 比较陌生。我编写了一个包含基本功能的 lib ,我会不断地填充新功能,并将其用于其他像这个这样的小项目。

我听说了 Valgrind 并决定用它检查我的程序,但不太明白为什么我有这么多泄漏,我觉得我所有的 malloc 都受到保护当使用使用 malloc 本身的函数时,与 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);
    }
}

最佳答案

使用完后免费线路,例如:

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

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

关于c - C 中 malloc 的内存泄漏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486513/

相关文章:

arrays - 查找数组的长度和指针指向数组的长度

c++ - 默认 Win32 项目具有恒定数量的内存泄漏

c - 另一个 malloc/free 困境

与 malloc 混淆。创建具有 4 个槽的字符串数组

javascript - 如何修复这个window.open IE内存泄漏?

c++ - 是否有可能 malloc() 分配的缓冲区与使用 mmap() 分配的另一个缓冲区重叠?

C 中基于控制台的应用程序,需要表格格式化程序

c - c中指向字符串的概念

c++ - 为什么不允许使用 "second C linkage of overloaded function"?

c++ - cvCaptureFromCAM 中存在内存泄漏吗?