Skip to content

Fix #1473: warn when fclose() is used as a while loop condition#8444

Open
francois-berder wants to merge 3 commits intocppcheck-opensource:mainfrom
francois-berder:pr-1473
Open

Fix #1473: warn when fclose() is used as a while loop condition#8444
francois-berder wants to merge 3 commits intocppcheck-opensource:mainfrom
francois-berder:pr-1473

Conversation

@francois-berder
Copy link
Copy Markdown
Collaborator

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.

…oop 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>
@sonarqubecloud
Copy link
Copy Markdown

Comment thread test/testio.cpp
Comment thread lib/checkio.cpp
const Token* bodyEnd = nullptr;
const Token* bodyStart = nullptr;

if (Token::simpleMatch(loopTok->previous(), "}")) { // Handle do-while loops
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it doesn't have to be a do-while when previous token is a "}".

Comment thread lib/checkio.cpp
operation = Filepointer::Operation::CLOSE;

// #1473 Check if fclose is in a while loop condition
if (fileTok) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the old code does not use AST so it doesn't handle well when the parameter is some expression.
imagine:

    while (i < 10 && fclose(f[i++]) {}

It is ugly code. I suggest you check that fileTok is just a simple variable token.

Comment thread lib/checkio.cpp
}

// Do not trigger a warning if the loop always exits or if the file is opened again in the loop.
if (!isReturnScope(bodyEnd, mSettings->library) && Token::findmatch(bodyStart, "%var% = fopen|freopen", bodyEnd, fileTok->varId()) == nullptr)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if there is any f = some_function(); in the loop we shouldn't warn. I suggest:

Suggested change
if (!isReturnScope(bodyEnd, mSettings->library) && Token::findmatch(bodyStart, "%var% = fopen|freopen", bodyEnd, fileTok->varId()) == nullptr)
if (!isReturnScope(bodyEnd, mSettings->library) && Token::findmatch(bodyStart, "%var% =", bodyEnd, fileTok->varId()) == nullptr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants