Skip to content

Commit 0838cbc

Browse files
peffgitster
authored andcommitted
tempfile: avoid "ferror | fclose" trick
The current code wants to record an error condition from either ferror() or fclose(), but makes sure that we always call both functions. So it can't use logical-OR "||", which would short-circuit when ferror() is true. Instead, it uses bitwise-OR "|" to evaluate both functions and set one or more bits in the "err" flag if they reported a failure. Unlike logical-OR, though, bitwise-OR does not introduce a sequence point, and the order of evaluation for its operands is unspecified. So a compiler would be free to generate code which calls fclose() first, and then ferror() on the now-freed filehandle. There's no indication that this has happened in practice, but let's write it out in a way that follows the standard. Noticed-by: Andreas Schwab <[email protected]> Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent c3808ca commit 0838cbc

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

tempfile.c

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -247,12 +247,8 @@ int close_tempfile(struct tempfile *tempfile)
247247
tempfile->fd = -1;
248248
if (fp) {
249249
tempfile->fp = NULL;
250-
251-
/*
252-
* Note: no short-circuiting here; we want to fclose()
253-
* in any case!
254-
*/
255-
err = ferror(fp) | fclose(fp);
250+
err = ferror(fp);
251+
err |= fclose(fp);
256252
} else {
257253
err = close(fd);
258254
}

0 commit comments

Comments
 (0)