From b53cd50f20705e35777401065c4295c34c83c11a Mon Sep 17 00:00:00 2001 From: chrchr-github Date: Sat, 10 Feb 2024 12:42:10 +0100 Subject: [PATCH] Fix #12422 False positive: subtracting pointers in same struct --- lib/checkother.cpp | 2 ++ test/testother.cpp | 10 +++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index fa43aba816a..deb39723195 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -3801,6 +3801,8 @@ void CheckOther::checkComparePointers() continue; if (v1.tokvalue->varId() == v2.tokvalue->varId()) continue; + if (var1->scope() == var2->scope() && var1->scope()->isClassOrStructOrUnion()) + continue; if (var1->isReference() || var2->isReference()) continue; if (var1->isRValueReference() || var2->isRValueReference()) diff --git a/test/testother.cpp b/test/testother.cpp index 4f12bf4f622..0e393c0fedb 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -11549,7 +11549,6 @@ class TestOther : public TestFixture { " return xp > yp;\n" "}"); ASSERT_EQUALS( - "[test.cpp:1] -> [test.cpp:5] -> [test.cpp:1] -> [test.cpp:6] -> [test.cpp:7]: (error) Comparing pointers that point to different objects\n" "[test.cpp:5]: (style) Variable 'xp' can be declared as pointer to const\n" "[test.cpp:6]: (style) Variable 'yp' can be declared as pointer to const\n" "[test.cpp:5]: (style) Variable 'xp' can be declared as pointer to const\n" // duplicate @@ -11646,6 +11645,15 @@ class TestOther : public TestFixture { "}\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()); + + check("struct S {\n" // #12422 + " int a, b;\n" + "};\n" + "void f() {\n" + " S s{};\n" + " size_t x = static_cast(reinterpret_cast(&s.b) - reinterpret_cast(&s.a));\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void unusedVariableValueTemplate() {