BufferOverrun: Improved error message when array index is used before checking that its in limits

This commit is contained in:
Daniel Marjamäki 2014-01-17 18:56:46 +01:00
parent b2b5590f2b
commit 18d6285ad2
3 changed files with 17 additions and 5 deletions

View File

@ -63,6 +63,19 @@ void CheckBufferOverrun::arrayIndexOutOfBoundsError(const Token *tok, const Arra
reportError(tok, Severity::error, "arrayIndexOutOfBounds", oss.str());
}
void CheckBufferOverrun::arrayIndexOutOfBoundsError(const Token *tok, const ArrayInfo &arrayInfo, const ValueFlow::Value &index)
{
std::ostringstream errmsg;
errmsg << "Array '" << arrayInfo.varname() << "[" << arrayInfo.num(0)
<< "]' accessed at index " << index.intvalue << ", which is out of bounds.";
if (index.condition)
errmsg << " Otherwise condition '" << index.condition->expressionString() << "' is redundant.";
reportError(tok, Severity::error, "arrayIndexOutOfBounds", errmsg.str());
}
void CheckBufferOverrun::arrayIndexOutOfBoundsError(const std::list<const Token *> &callstack, const ArrayInfo &arrayInfo, const std::vector<MathLib::bigint> &index)
{
std::ostringstream oss;
@ -1138,14 +1151,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const ArrayInfo &arrayInfo
continue;
}
else if (Token::Match(tok, "%varid% [", arrayInfo.declarationId()) && tok->next()->astOperand2() && !tok->next()->astOperand2()->values.empty()) {
else if (arrayInfo.num().size() == 1U && Token::Match(tok, "%varid% [", arrayInfo.declarationId()) && tok->next()->astOperand2() && !tok->next()->astOperand2()->values.empty()) {
const std::list<ValueFlow::Value> &values = tok->next()->astOperand2()->values;
std::list<ValueFlow::Value>::const_iterator it;
for (it = values.begin(); it != values.end(); ++it) {
if (it->intvalue >= arrayInfo.num()[0]) {
std::vector<MathLib::bigint> indexes;
indexes.push_back(it->intvalue);
arrayIndexOutOfBoundsError(tok, arrayInfo, indexes);
arrayIndexOutOfBoundsError(tok, arrayInfo, *it);
}
}
}

View File

@ -211,6 +211,7 @@ public:
void checkFunctionCall(const Token *tok, const ArrayInfo &arrayInfo, std::list<const Token *> callstack);
void arrayIndexOutOfBoundsError(const Token *tok, const ArrayInfo &arrayInfo, const std::vector<MathLib::bigint> &index);
void arrayIndexOutOfBoundsError(const Token *tok, const ArrayInfo &arrayInfo, const ValueFlow::Value &index);
void arrayIndexInForLoop(const Token *tok, const ArrayInfo &arrayInfo);
private:

View File

@ -2062,7 +2062,7 @@ private:
" str[i] = 0;\n"
" if (i==10) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'str[3]' accessed at index 10, which is out of bounds.\n", errout.str());
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'str[3]' accessed at index 10, which is out of bounds. Otherwise condition 'i==10' is redundant.\n", errout.str());
}
void buffer_overrun_1_standard_functions() {