grep: Reuse allocated buffers

This commit is contained in:
sin 2014-12-16 20:20:41 +00:00
parent 7e8fcc1f03
commit fb85f99c0a

12
grep.c
View File

@ -177,15 +177,15 @@ addpattern(const char *pattern)
static void static void
addpatternfile(FILE *fp) addpatternfile(FILE *fp)
{ {
char *buf = NULL; static char *buf = NULL;
size_t len = 0, size = 0; static size_t size = 0;
size_t len = 0;
while ((len = getline(&buf, &size, fp)) != -1) { while ((len = getline(&buf, &size, fp)) != -1) {
if (len && buf[len - 1] == '\n') if (len && buf[len - 1] == '\n')
buf[len - 1] = '\0'; buf[len - 1] = '\0';
addpattern(buf); addpattern(buf);
} }
free(buf);
if (ferror(fp)) if (ferror(fp))
enprintf(Error, "read error:"); enprintf(Error, "read error:");
} }
@ -193,8 +193,9 @@ addpatternfile(FILE *fp)
static int static int
grep(FILE *fp, const char *str) grep(FILE *fp, const char *str)
{ {
char *buf = NULL; static char *buf = NULL;
size_t len = 0, size = 0; static size_t size = 0;
size_t len = 0;
long c = 0, n; long c = 0, n;
struct pattern *pnode; struct pattern *pnode;
int match = NoMatch; int match = NoMatch;
@ -250,6 +251,5 @@ end:
weprintf("%s: read error:", str); weprintf("%s: read error:", str);
match = Error; match = Error;
} }
free(buf);
return match; return match;
} }