Skip to content

Commit

Permalink
Close the input FILE * in read_file() and the output FILE * in write_…
Browse files Browse the repository at this point in the history
…file()

if read_stream() or write_stream() fails to avoid leaking the FILE.

Reported by:	Coverity
CID:		977702
Reviewed by:	pfg
MFC after:	1 week
Differential Revision:	https://reviews.freebsd.org/D6554
  • Loading branch information
DonLewisFreeBSD committed May 25, 2016
1 parent 360ba6b commit 92a58a9
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions bin/ed/io.c
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,24 @@ read_file(char *fn, long n)
{
FILE *fp;
long size;

int cs;

fp = (*fn == '!') ? popen(fn + 1, "r") : fopen(strip_escapes(fn), "r");
if (fp == NULL) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "cannot open input file";
return ERR;
} else if ((size = read_stream(fp, n)) < 0)
return ERR;
else if (((*fn == '!') ? pclose(fp) : fclose(fp)) < 0) {
}
if ((size = read_stream(fp, n)) < 0) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "error reading input file";
}
if ((cs = (*fn == '!') ? pclose(fp) : fclose(fp)) < 0) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "cannot close input file";
return ERR;
}
if (size < 0 || cs < 0)
return ERR;
if (!scripted)
fprintf(stdout, "%lu\n", size);
return current_addr - n;
Expand Down Expand Up @@ -143,19 +147,24 @@ write_file(char *fn, const char *mode, long n, long m)
{
FILE *fp;
long size;
int cs;

fp = (*fn == '!') ? popen(fn+1, "w") : fopen(strip_escapes(fn), mode);
if (fp == NULL) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "cannot open output file";
return ERR;
} else if ((size = write_stream(fp, n, m)) < 0)
return ERR;
else if (((*fn == '!') ? pclose(fp) : fclose(fp)) < 0) {
}
if ((size = write_stream(fp, n, m)) < 0) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "error writing output file";
}
if ((cs = (*fn == '!') ? pclose(fp) : fclose(fp)) < 0) {
fprintf(stderr, "%s: %s\n", fn, strerror(errno));
errmsg = "cannot close output file";
return ERR;
}
if (size < 0 || cs < 0)
return ERR;
if (!scripted)
fprintf(stdout, "%lu\n", size);
return n ? m - n + 1 : 0;
Expand Down

0 comments on commit 92a58a9

Please sign in to comment.