#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("%sn", buf);
return (buf - cnt - 1);
}
当我编译没有标志时,我只得到两个空行。使用-fsanitize=address编译,我知道heap-buffer-overflow发生在printf("%sn", buf);
但是我不知道为什么会这样。我尝试STDIN来修复它,但没有工作。有人能帮我检查一下吗?
-
您不能用null字符终止
buf
*buf = 'n'; *buf = ' ';
确保你储备空间
null
字符而分配内存buf
。 -
如果读取的字节数小于0,则释放内存
if (nread < 0) { return (NULL); }
if (nread < 0) { free(startAddress); return (NULL); }
-
您可以使用临时指针来保存
buf
的起始地址,而不是计算起始地址。
char *get_next_line(int fd)
{
char *buf;
char c;
int nread;
if (fd < 0 || BUFFER_SIZE < 1)
return (NULL);
buf = (char*)malloc(BUFFER_SIZE + 2);
if (!buf)
return (NULL);
char *startAddress = buf;
while(nread = (read(fd, &c, 1)) > 0)
{
*buf = c;
buf++;
if (c == 'n')
break;
}
if (nread < 0) {
free(startAddress);
return (NULL);
}
*buf = ' ';
printf("%sn", buf);
return startAddress;
}