【发布时间】:2019-04-28 10:00:24
【问题描述】:
我对@987654321@ 和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 我怎样才能
freereturn需要什么? -
你会在用完之后释放它,而不是在你归还它的时候。
-
您没有使用
realloc来扩展*line的大小 - 您一直在为其分配新的内存块并失去对旧内存的跟踪。
标签: c memory-leaks malloc