From fb8888381367c068a7837e1e62677b849abfbf73 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Thu, 23 Feb 2023 17:27:47 +0100 Subject: [PATCH] Fix #11576 FP comparePointers / FN cstyleCast when taking address (#4817) * Fix FN cstyleCast when taking address * Fix #11576 FP comparePointers with member variable * Use getParentLifetime() * Fix test case number --- lib/checkother.cpp | 8 +++++++- test/testother.cpp | 17 +++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 8eb5097d0..49e5052ae 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -303,7 +303,7 @@ void CheckOther::warningOldStylePointerCast() tok = scope->bodyStart; for (; tok && tok != scope->bodyEnd; tok = tok->next()) { // Old style pointer casting.. - if (!Token::Match(tok, "( const|volatile| const|volatile|class|struct| %type% * *| *| const|&| ) (| %name%|%num%|%bool%|%char%|%str%")) + if (!Token::Match(tok, "( const|volatile| const|volatile|class|struct| %type% * *| *| const|&| ) (| %name%|%num%|%bool%|%char%|%str%|&")) continue; if (Token::Match(tok->previous(), "%type%")) continue; @@ -3685,6 +3685,12 @@ void CheckOther::checkComparePointers() continue; if (var1->isRValueReference() || var2->isRValueReference()) continue; + if (const Token* parent2 = getParentLifetime(mTokenizer->isCPP(), v2.tokvalue, &mSettings->library)) + if (var1 == parent2->variable()) + continue; + if (const Token* parent1 = getParentLifetime(mTokenizer->isCPP(), v1.tokvalue, &mSettings->library)) + if (var2 == parent1->variable()) + continue; comparePointersError(tok, &v1, &v2); } } diff --git a/test/testother.cpp b/test/testother.cpp index 705ed5012..9fead3abe 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -2653,7 +2653,7 @@ private: " U* y = (U*)(&x)\n" " y->mutate();\n" //to avoid warnings that y can be const "}"); - ASSERT_EQUALS("", errout.str()); + ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str()); check("struct C { void f() const; };\n" // #9875 - crash "\n" @@ -5159,7 +5159,7 @@ private: } void testMisusedScopeObjectNamespace() { - check("namespace M {\n" // #4479 + check("namespace M {\n" // #4779 " namespace N {\n" " struct S {};\n" " }\n" @@ -10653,6 +10653,19 @@ private: " return xp > yp;\n" "}"); ASSERT_EQUALS("", errout.str()); + + check("struct S { int i; };\n" // #11576 + "int f(S s) {\n" + " return &s.i - (int*)&s;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3]: (style) C-style pointer casting\n", errout.str()); + + check("struct S { int i; };\n" + "int f(S s1, S s2) {\n" + " return &s1.i - reinterpret_cast(&s2);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:3]: (error) Subtracting pointers that point to different objects\n", + errout.str()); } void unusedVariableValueTemplate() {