From dc7550ed9fc1553705429045eeb3a27b308a2f81 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Sat, 13 May 2023 14:09:47 +0200 Subject: [PATCH] Assign values to pointers with C++11 init (#5055) * Assign values to pointers with C++11 init * Handle assigning empty init list --- lib/valueflow.cpp | 7 ++++++- test/testvalueflow.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 3ac36a696..2bb5a6f29 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -1343,6 +1343,11 @@ static Token * valueFlowSetConstantValue(Token *tok, const Settings *settings, b if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings, isInitList); + } else if (Token::Match(tok, "%name% = { }") && tok->variable() && + (tok->variable()->isPointer() || (tok->variable()->valueType() && tok->variable()->valueType()->isIntegral()))) { + ValueFlow::Value value(0); + value.setKnown(); + setTokenValue(tok->tokAt(2), std::move(value), settings, isInitList); } return tok->next(); } @@ -5814,7 +5819,7 @@ static void valueFlowAfterAssign(TokenList *tokenlist, if (tok->str() != "=" && !(isInit = isVariableInit(tok))) continue; - if (tok->astParent() && !(tok->astParent()->str() == ";" && astIsLHS(tok))) + if (tok->astParent() && !((tok->astParent()->str() == ";" && astIsLHS(tok)) || tok->astParent()->str() == "*")) continue; // Lhs should be a variable diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 350716a79..f03d4be37 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -5054,6 +5054,46 @@ private: ASSERT_EQUALS(true, value.isKnown()); ASSERT_EQUALS(1, value.intvalue); + code = "bool f() {\n" + " int* p{};\n" + " return p == nullptr;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + + code = "bool f() {\n" + " int* p{ nullptr };\n" + " return p == nullptr;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + + code = "bool f() {\n" + " int* p{ 0 };\n" + " return p == nullptr;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + + code = "bool f() {\n" + " int* p = {};\n" + " return p == nullptr;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + + code = "bool f() {\n" + " int i = {};\n" + " return i == 0;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + // calculation with known result code = "int f(int x) { a = x & 0; }"; // <- & is 0 value = valueOfTok(code, "&");