commit 5b51c335a0e4642ea15aca1b66fae95c242e687d
parent 99e4f82543be7a4ebafa993e17acbf0ee3c90ec9
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date: Tue, 1 Dec 2015 21:31:55 +0100
Avoid memory and file leak in doread()
inject() can call to error(), and there is also a direct
call to error() in doread(), and we are open and allocating
memory there, so we can have memory leaks there. The best
option is making statics s and fp and then the memory
leaks will be controlled in the next iteration.
Diffstat:
M | ed.c | | | 22 | ++++++++++++---------- |
1 file changed, 12 insertions(+), 10 deletions(-)
diff --git a/ed.c b/ed.c
@@ -448,34 +448,36 @@ dowrite(char *fname, int trunc)
static void
doread(char *fname)
{
- FILE *fp;
size_t len = 0, cnt;
ssize_t n;
- char *s = NULL, *p;
+ char *p;
+ FILE *aux;
+ static char *s;
+ static FILE *fp;
+ if (fp)
+ fclose(fp);
if (!savfname)
setfname(fname);
if (!(fp = fopen(fname, "r")))
error("input/output error");
+
curln = line2;
for (cnt = 0; (n = getline(&s, &len, fp)) > 0; cnt += (size_t)n) {
if (s[n-1] != '\n') {
- if (len == SIZE_MAX ||
- !(p = realloc(s, ++len)))
+ if (len == SIZE_MAX || !(p = realloc(s, ++len)))
error("out of memory");
s = p;
s[n-1] = '\n';
s[n] = '\0';
}
- /*
- * FIXME: if inject calls error we can have a
- * memory leak, and a file leak
- */
inject(s);
}
printf("%zu\n", cnt);
- free(s);
- if (fclose(fp))
+
+ aux = fp;
+ fp = NULL;
+ if (fclose(aux))
error("input/output error");
}