我对C
和malloc
比较陌生。我编写了一个包含基本功能的 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/