Skip to content

Commit 2a7412f

Browse files
ls-tetysclaude
authored andcommitted
Fix #15267 FN constVariablePointer when an alias of the pointer is moved with += or -=
Moving an alias of the pointer does not change the object, like assigning it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 61d2460 commit 2a7412f

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

‎lib/checkother.cpp‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1928,8 +1928,10 @@ static bool isConstPointerVariable(const Variable* p, const Settings& settings)
19281928
findVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, settings)) {
19291929
if (p->isReference())
19301930
return false;
1931-
// Assigning a pointer through another pointer may still be const
1932-
if (!Token::simpleMatch(tok->astParent(), "="))
1931+
// Assigning a pointer through another pointer may still be const; moving an alias (+=/-=)
1932+
// changes the pointer, not the pointee
1933+
if (!Token::simpleMatch(tok->astParent(), "=") &&
1934+
!(Token::Match(tok->astParent(), "+=|-=") && astIsPointer(tok)))
19331935
return false;
19341936
if (!astIsLHS(tok))
19351937
return false;

‎test/testother.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5096,6 +5096,26 @@ class TestOther : public TestFixture {
50965096
ASSERT_EQUALS("[test.cpp:3:8]: (style) Parameter 'p' can be declared as pointer to const [constParameterPointer]\n"
50975097
"[test.cpp:3:8]: (style) Parameter 'q' can be declared as pointer to const [constParameterPointer]\n",
50985098
errout_str());
5099+
5100+
check("int f(int** pp) {\n" // #15267
5101+
" int* s = *pp;\n"
5102+
" *pp += 2;\n"
5103+
" return *s;\n"
5104+
"}\n");
5105+
ASSERT_EQUALS("[test.cpp:2:10]: (style) Variable 's' can be declared as pointer to const [constVariablePointer]\n", errout_str());
5106+
5107+
check("int f(int* p) {\n"
5108+
" int* s = p;\n"
5109+
" p -= 2;\n"
5110+
" return *s;\n"
5111+
"}\n");
5112+
ASSERT_EQUALS("[test.cpp:2:10]: (style) Variable 's' can be declared as pointer to const [constVariablePointer]\n", errout_str());
5113+
5114+
check("void f(int* p) {\n" // writing through the alias changes the pointee
5115+
" int* s = p;\n"
5116+
" *p += 2;\n"
5117+
"}\n");
5118+
ASSERT_EQUALS("", errout_str());
50995119
}
51005120

51015121
void constArray() {

0 commit comments

Comments
 (0)