Skip to content

Commit 5fa3789

Browse files
Fix #1473: warn when fclose() is used as a while loop condition
Using fclose() as a while loop condition closes the file on every iteration and operates on an already-closed file handle from the second iteration onward. Signed-off-by: Francois Berder <fberder@outlook.fr>
1 parent caff3d4 commit 5fa3789

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

lib/checkio.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,19 @@ void CheckIO::checkFileUsage()
245245
} else if (tok->str() == "fclose") {
246246
fileTok = tok->tokAt(2);
247247
operation = Filepointer::Operation::CLOSE;
248+
249+
// #1473 Check if fclose is in a while loop condition
250+
const Token* tmp = tok->astParent();
251+
const Token* loopTok = nullptr;
252+
while (tmp) {
253+
if (Token::simpleMatch(tmp->previous(), "while (")) {
254+
loopTok = tmp->previous();
255+
break;
256+
}
257+
tmp = tmp->astParent();
258+
}
259+
if (loopTok)
260+
useClosedFileError(tok);
248261
} else if (whitelist.find(tok->str()) != whitelist.end()) {
249262
fileTok = tok->tokAt(2);
250263
if ((tok->str() == "ungetc" || tok->str() == "ungetwc") && fileTok)

test/testio.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -544,7 +544,7 @@ class TestIO : public TestFixture {
544544
" FILE *a = fopen(\"aa\", \"r\");\n"
545545
" while (fclose(a)) {}\n"
546546
"}");
547-
TODO_ASSERT_EQUALS("[test.cpp:3:5]: (error) Used file that is not opened. [useClosedFile]\n", "", errout_str());
547+
ASSERT_EQUALS("[test.cpp:3:12]: (error) Used file that is not opened. [useClosedFile]\n", errout_str());
548548

549549
// #6823
550550
check("void foo() {\n"

0 commit comments

Comments
 (0)