Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New check: eraseIteratorOutOfBounds #5913

Merged
merged 15 commits into from
Feb 4, 2024
4 changes: 3 additions & 1 deletion lib/astutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3019,8 +3019,10 @@ const Token* findExpressionChangedSkipDeadCode(const Token* expr,
const Token* getArgumentStart(const Token* ftok)
{
const Token* tok = ftok;
if (Token::Match(tok, "%name% (|{"))
if (Token::Match(tok, "%name% (|{|)"))
tok = ftok->next();
while (Token::simpleMatch(tok, ")"))
tok = tok->next();
if (!Token::Match(tok, "(|{|["))
return nullptr;
const Token* startTok = tok->astOperand2();
Expand Down
11 changes: 5 additions & 6 deletions lib/checkstl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3152,14 +3152,13 @@ void CheckStl::eraseIteratorOutOfBounds()
if (!tok->valueType())
continue;
const Library::Container* container = tok->valueType()->container;
if (!container)
continue;
if (!Token::Match(tok->next(), ". %name% ("))
if (!container || !Token::simpleMatch(tok->astParent(), "."))
continue;
const Library::Container::Action action = container->getAction(tok->strAt(2));
const Token* const ftok = tok->astParent()->astOperand2();
const Library::Container::Action action = container->getAction(ftok->str());
chrchr-github marked this conversation as resolved.
Show resolved Hide resolved
if (action != Library::Container::Action::ERASE)
continue;
const std::vector<const Token*> args = getArguments(tok->tokAt(2));
const std::vector<const Token*> args = getArguments(ftok);
if (args.size() != 1) // empty range is ok
continue;

Expand All @@ -3176,7 +3175,7 @@ void CheckStl::eraseIteratorOutOfBounds()
errVal = startVal;
}
if (errVal)
eraseIteratorOutOfBoundsError(tok->tokAt(2), args[0], errVal);
eraseIteratorOutOfBoundsError(ftok, args[0], errVal);
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions test/teststl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2192,6 +2192,13 @@ class TestStl : public TestFixture {
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Either the condition 'it==v.end()' is redundant or function 'erase()' is called on the iterator 'it' which is out of bounds.\n",
errout.str());

check("void f() {\n"
" std::vector<int> v;\n"
" ((v).erase)(v.begin());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Calling function 'erase()' on the iterator 'v.begin()' which is out of bounds.\n",
errout.str());
chrchr-github marked this conversation as resolved.
Show resolved Hide resolved
}

// Dereferencing invalid pointer
Expand Down
Loading