Skip to content

Commit a61f4e9

Browse files
committed
Fixed cppcheck-opensource#7831 (false-positive: terminateStrncpy)
1 parent b687e01 commit a61f4e9

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

lib/checkbufferoverrun.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -987,10 +987,12 @@ void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arr
987987
for (; tok4; tok4 = tok4->next()) {
988988
const Token* tok3 = tok2->tokAt(2);
989989
if (tok4->varId() == tok3->varId()) {
990-
if (!Token::Match(tok4, "%varid% [ %any% ] = 0 ;", tok3->varId())) {
990+
const Token *eq = nullptr;
991+
if (Token::Match(tok4, "%varid% [", tok3->varId()) && Token::simpleMatch(tok4->linkAt(1), "] ="))
992+
eq = tok4->linkAt(1)->next();
993+
const Token *rhs = eq ? eq->astOperand2() : nullptr;
994+
if (!(rhs && rhs->hasKnownIntValue() && rhs->getValue(0)))
991995
terminateStrncpyError(tok2, tok3->str());
992-
}
993-
994996
break;
995997
}
996998
}

test/testbufferoverrun.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3431,6 +3431,20 @@ class TestBufferOverrun : public TestFixture {
34313431
"}");
34323432
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'baz' may not be null-terminated after the call to strncpy().\n", errout.str());
34333433

3434+
check("void foo ( char *bar ) {\n"
3435+
" char baz[100];\n"
3436+
" strncpy(baz, bar, 100);\n"
3437+
" baz[99] = '\\0';\n"
3438+
"}");
3439+
ASSERT_EQUALS("", errout.str());
3440+
3441+
check("void foo ( char *bar ) {\n"
3442+
" char baz[100];\n"
3443+
" strncpy(baz, bar, 100);\n"
3444+
" baz[x+1] = '\\0';\n"
3445+
"}");
3446+
ASSERT_EQUALS("", errout.str());
3447+
34343448
// Test with invalid code that there is no segfault
34353449
check("char baz[100];\n"
34363450
"strncpy(baz, \"var\", 100)\n");

0 commit comments

Comments
 (0)