【发布时间】:2021-11-30 06:02:49
【问题描述】:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
char *get_next_line(int fd);
int main (void)
{
int i = 0;
char *s;
int fd;
fd = open("./text", O_RDONLY);
s = get_next_line (fd);
}
char *get_next_line(int fd)
{
char *buf;
char c;
int nread;
int cnt;
if (fd < 0 || BUFFER_SIZE < 1)
return (NULL);
buf = (char*)malloc(BUFFER_SIZE + 1);
if (!buf)
return (NULL);
while(nread = (read(fd, &c, 1)) > 0)
{
*buf = c;
buf++;
cnt++;
if (c == '\n')
break;
}
if (nread < 0)
return (NULL);
*buf = '\n';
printf("%s\n", buf);
return (buf - cnt - 1);
}
当我在没有标志的情况下编译时,我只得到两个空行。使用 -fsanitize=address 编译,我知道 heap-buffer-overflow 发生在 printf("%s\n", buf);
但我不知道为什么会这样。我尝试了 STDIN 来修复它,但没有奏效。有人可以检查一下吗?
【问题讨论】:
-
如果函数返回除
buf之外的任何内容,您也会得到泄漏,因为没有人再跟踪该段的起始地址。
标签: c heap-memory