simplify resource cleanup upon errors in get_filestream_info()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
diff --git a/tog/tog.c b/tog/tog.c
index c75199b..5a7f312 100644
--- a/tog/tog.c
+++ b/tog/tog.c
@@ -3022,6 +3022,7 @@ const struct got_error *
get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
FILE *infile)
{
+ const struct got_error *err = NULL;
size_t len;
char *buf = NULL;
int i;
@@ -3050,8 +3051,8 @@ get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
fread(buf, 1, len, infile);
if (ferror(infile)) {
- free(buf);
- return got_error_from_errno("fread");
+ err = got_error_from_errno("fread");
+ goto done;
}
i = 0;
@@ -3062,10 +3063,8 @@ get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
*nlines = 1;
*line_offsets = calloc(1, sizeof(**line_offsets));
if (*line_offsets == NULL) {
- free(buf);
- free(*line_offsets);
- *line_offsets = NULL;
- return got_error_from_errno("calloc");
+ err = got_error_from_errno("calloc");
+ goto done;
}
/* Skip forward over end of first line. */
while (i < len) {
@@ -3086,10 +3085,9 @@ get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
noffsets, *nlines,
sizeof(**line_offsets));
if (o == NULL) {
- free(*line_offsets);
- *line_offsets = NULL;
- return got_error_from_errno(
+ err = got_error_from_errno(
"recallocarray");
+ goto done;
}
*line_offsets = o;
noffsets = *nlines;
@@ -3101,19 +3099,25 @@ get_filestream_info(size_t *filesize, int *nlines, off_t **line_offsets,
}
if (fflush(infile) != 0) {
- free(buf);
- free(*line_offsets);
- *line_offsets = NULL;
- return got_error_from_errno("fflush");
+ err = got_error_from_errno("fflush");
+ goto done;
}
rewind(infile);
if (filesize)
*filesize = len;
-
+done:
free(buf);
- free(*line_offsets);
- *line_offsets = NULL;
+ if (err) {
+ if (line_offsets) {
+ free(*line_offsets);
+ *line_offsets = NULL;
+ }
+ if (filesize)
+ *filesize = 0;
+ if (nlines)
+ *nlines = 0;
+ }
return NULL;
}