libutil/getlines: fix potential crash

linelen was uninitialized if for example:

$ > empty
$ sort ls.c empty
This commit is contained in:
Hiltjo Posthuma 2015-05-08 17:10:39 +02:00 committed by sin
parent e3cdcce2ec
commit 29649762b3

View File

@ -10,7 +10,7 @@ void
getlines(FILE *fp, struct linebuf *b)
{
char *line = NULL;
size_t size = 0, linelen;
size_t size = 0, linelen = 0;
ssize_t len;
while ((len = getline(&line, &size, fp)) > 0) {
@ -22,7 +22,7 @@ getlines(FILE *fp, struct linebuf *b)
b->lines[b->nlines - 1] = memcpy(emalloc(linelen + 1), line, linelen + 1);
}
free(line);
if (b->lines && b->nlines && b->lines[b->nlines - 1][linelen - 1] != '\n') {
if (b->lines && b->nlines && linelen && b->lines[b->nlines - 1][linelen - 1] != '\n') {
b->lines[b->nlines - 1] = erealloc(b->lines[b->nlines - 1], linelen + 2);
b->lines[b->nlines - 1][linelen] = '\n';
b->lines[b->nlines - 1][linelen + 1] = '\0';