Skip to content

Commit 865df4e

Browse files
committed
Fixed false negative danmar#4306: Detect loop access of empty STL container
1 parent 5ddee75 commit 865df4e

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/checkstl.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1551,10 +1551,14 @@ void CheckStl::readingEmptyStlContainer()
15511551
if (i->type != Scope::eFunction)
15521552
continue;
15531553

1554+
const Token* restartTok = nullptr;
15541555
for (const Token *tok = i->classStart->next(); tok != i->classEnd; tok = tok->next()) {
1555-
if (Token::Match(tok, "for|while|do|}")) { // Loops and end of scope clear the sets.
1556+
if (Token::Match(tok, "for|while")) { // Loops and end of scope clear the sets.
1557+
restartTok = tok->linkAt(1); // Check condition to catch looping over empty containers
1558+
} else if (tok == restartTok || Token::Match(tok, "do|}")) {
15561559
empty_map.clear();
15571560
empty_nonmap.clear();
1561+
restartTok = nullptr;
15581562
}
15591563

15601564
if (!tok->varId())

test/teststl.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2565,6 +2565,13 @@ class TestStl : public TestFixture {
25652565
" std::string strValue2 = CMap[1];\n"
25662566
"}\n", true);
25672567
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Reading from empty STL container\n", errout.str());
2568+
2569+
// #4306
2570+
check("void f(std::vector<int> v) {\n"
2571+
" v.clear();\n"
2572+
" for(int i = 0; i < v.size(); i++) { cout << v[i]; }\n"
2573+
"}", true);
2574+
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Reading from empty STL container\n", errout.str());
25682575
}
25692576
};
25702577

0 commit comments

Comments
 (0)