From a61f4e9c94ab4ca0caa25f05f53b478ce4dafec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Thu, 24 Nov 2016 07:04:58 +0100 Subject: [PATCH] Fixed #7831 (false-positive: terminateStrncpy) --- lib/checkbufferoverrun.cpp | 8 +++++--- test/testbufferoverrun.cpp | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index d6341f6ef..79fd99fdb 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -987,10 +987,12 @@ void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arr for (; tok4; tok4 = tok4->next()) { const Token* tok3 = tok2->tokAt(2); if (tok4->varId() == tok3->varId()) { - if (!Token::Match(tok4, "%varid% [ %any% ] = 0 ;", tok3->varId())) { + const Token *eq = nullptr; + if (Token::Match(tok4, "%varid% [", tok3->varId()) && Token::simpleMatch(tok4->linkAt(1), "] =")) + eq = tok4->linkAt(1)->next(); + const Token *rhs = eq ? eq->astOperand2() : nullptr; + if (!(rhs && rhs->hasKnownIntValue() && rhs->getValue(0))) terminateStrncpyError(tok2, tok3->str()); - } - break; } } diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index f338adbbc..32e4baf09 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -3431,6 +3431,20 @@ private: "}"); ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) The buffer 'baz' may not be null-terminated after the call to strncpy().\n", errout.str()); + check("void foo ( char *bar ) {\n" + " char baz[100];\n" + " strncpy(baz, bar, 100);\n" + " baz[99] = '\\0';\n" + "}"); + ASSERT_EQUALS("", errout.str()); + + check("void foo ( char *bar ) {\n" + " char baz[100];\n" + " strncpy(baz, bar, 100);\n" + " baz[x+1] = '\\0';\n" + "}"); + ASSERT_EQUALS("", errout.str()); + // Test with invalid code that there is no segfault check("char baz[100];\n" "strncpy(baz, \"var\", 100)\n");