Skip to content

Commit 0a5b103

Browse files
Fix #14496 FN variableScope with nullptr (#8221)
1 parent 24c7f0b commit 0a5b103

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

lib/checkother.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,8 @@ static bool isSimpleExpr(const Token* tok, const Variable* var, const Settings&
11631163
return false;
11641164
if (tok->isNumber() || tok->tokType() == Token::eString || tok->tokType() == Token::eChar || tok->isBoolean())
11651165
return true;
1166+
if (isNullOperand(tok))
1167+
return true;
11661168
bool needsCheck = tok->varId() > 0;
11671169
if (!needsCheck) {
11681170
if (tok->isArithmeticalOp())

test/testother.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ class TestOther : public TestFixture {
121121
TEST_CASE(varScope41); // #11845
122122
TEST_CASE(varScope42);
123123
TEST_CASE(varScope43);
124+
TEST_CASE(varScope44);
124125

125126
TEST_CASE(oldStylePointerCast);
126127
TEST_CASE(intToPointerCast);
@@ -1945,6 +1946,32 @@ class TestOther : public TestFixture {
19451946
ASSERT_EQUALS("[test.cpp:3:12]: (style) The scope of the variable 'x' can be reduced. [variableScope]\n", errout_str());
19461947
}
19471948

1949+
void varScope44() { // #14496
1950+
check("char* f() {\n"
1951+
" char* p = nullptr;\n"
1952+
" {\n"
1953+
" p = strdup(\"abc\");\n"
1954+
" if (p) {\n"
1955+
" return p;\n"
1956+
" }\n"
1957+
" }\n"
1958+
" return nullptr;\n"
1959+
"}\n"
1960+
"char* g() {\n"
1961+
" char* q = NULL;\n"
1962+
" {\n"
1963+
" q = strdup(\"abc\");\n"
1964+
" if (q) {\n"
1965+
" return q;\n"
1966+
" }\n"
1967+
" }\n"
1968+
" return nullptr;\n"
1969+
"}\n");
1970+
ASSERT_EQUALS("[test.cpp:2:11]: (style) The scope of the variable 'p' can be reduced. [variableScope]\n"
1971+
"[test.cpp:12:11]: (style) The scope of the variable 'q' can be reduced. [variableScope]\n",
1972+
errout_str());
1973+
}
1974+
19481975
#define checkOldStylePointerCast(...) checkOldStylePointerCast_(__FILE__, __LINE__, __VA_ARGS__)
19491976
template<size_t size>
19501977
void checkOldStylePointerCast_(const char* file, int line, const char (&code)[size], Standards::cppstd_t std = Standards::CPPLatest) {

0 commit comments

Comments
 (0)