]> Devi Nivas Git - cs3210-lab0.git/commitdiff
Fix missing NUL-terminator in grep
authorAustin Clements <amdragon@mit.edu>
Wed, 25 Mar 2015 00:54:39 +0000 (20:54 -0400)
committerAustin Clements <amdragon@mit.edu>
Wed, 25 Mar 2015 00:54:39 +0000 (20:54 -0400)
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.

grep.c

diff --git a/grep.c b/grep.c
index 2fbf5b6cb1f6ada1095f6bd21562057de5552840..28ff11a8da3f5a2c505c7e4ccf82370e6ed31843 100644 (file)
--- a/grep.c
+++ b/grep.c
@@ -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;