Skip to content

Commit

Permalink
Fix missing NUL-terminator in grep
Browse files Browse the repository at this point in the history
Currently, grep read()s into a buffer and then uses the buffer as a
string. Since there's no NUL-terminator, this can cause it to falsely
identify line breaks and matches from leftover data on earlier lines
and, if a line fills up the entire buffer, to read past the end of the
buffer.

Fix this by NUL-terminating any data returned by read().

Thanks to Keiichi Watanabe for the report.
  • Loading branch information
Austin Clements committed Mar 25, 2015
1 parent 3d2dedd commit 7443b96
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion grep.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ grep(char *pattern, int fd)
char *p, *q;

m = 0;
while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){
while((n = read(fd, buf+m, sizeof(buf)-m-1)) > 0){
m += n;
buf[m] = '\0';
p = buf;
while((q = strchr(p, '\n')) != 0){
*q = 0;
Expand Down

0 comments on commit 7443b96

Please sign in to comment.