Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion lib/checkuninitvar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@ bool CheckUninitVarImpl::checkScopeForVariable(const Token *tok, const Variable&
}
}
}
if (Token::simpleMatch(parent->astParent(), "=") && astIsLHS(parent)) {
if (parent->astParent() && parent->astParent()->isAssignmentOp() && astIsLHS(parent)) {
const Token *eq = parent->astParent();
if (const Token *errorToken = checkExpr(eq->astOperand2(), var, *alloc, number_of_if==0)) {
if (!suppressErrors)
Expand Down Expand Up @@ -1295,6 +1295,27 @@ const Token* CheckUninitVarImpl::isVariableUsage(const Token *vartok, const Libr
}
if (alloc != NO_ALLOC && astIsRhs(valueExpr))
return nullptr;
} else if (tok->astParent() && (tok->astParent()->isAssignmentOp() || tok->astParent()->isIncDecOp())) {
// NO_ALLOC -> no matter what we read the uninitialized memory.
// pointer/array -> safe, as long as we don't dereference
//
// sometimes "pointer" and "alloc == ARRAY" are used for things
// that aren't actually pointers or arrays.
//
// this test
// ctu("void increment(int& i) { ++i; }\n" // #6475
// uses the callback which hardcodes pointer = true and alloc = ARRAY
// though int& isn't a pointer or an array, and we expect this
// function to not return nullptr even though i is not dereferenced
bool isPtr = pointer;
bool isArr = alloc == ARRAY;
if (vartok && vartok->variable()) {
isPtr = vartok->variable()->isPointer();
isArr = vartok->variable()->isArray();
}
if ((alloc != NO_ALLOC) && ((isPtr || isArr) && !derefValue)) {
return nullptr;
}
}
}

Expand Down
31 changes: 31 additions & 0 deletions test/testuninitvar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2202,6 +2202,37 @@ class TestUninitVar : public TestFixture {
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());


checkUninitVar("void f() {\n"
" char *p = new char;\n"
" p += 1;\n"
" delete (p - 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());

checkUninitVar("void f() {\n"
" char *buf = (char *)malloc(1);\n"
" if (!buf)\n"
" return NULL;\n"
" buf += buf[0];\n"
" free(buf);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5:15]: (error) Memory is allocated but not initialized: buf[0] [uninitdata]\n", errout_str());

checkUninitVar("void g() {\n"
" int* p = new int;\n"
" p++;\n"
" delete (p - 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());

checkUninitVar("void g() {\n"
" int* p = new int;\n"
" ++p; // FP\n"
" delete (p - 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}

// class / struct..
Expand Down
Loading