added check for zero division. The code was written by Nguyen Duong Tuan

This commit is contained in:
Daniel Marjamäki 2009-03-28 07:49:47 +01:00
parent c0b608059a
commit 4059a2ad05
3 changed files with 73 additions and 0 deletions

View File

@ -962,6 +962,18 @@ void CheckOther::nullPointer()
void CheckOther::CheckZeroDivision()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (Token::simpleMatch(tok, "/ 0"))
zerodivWarning(tok);
}
}
void CheckOther::cstyleCastError(const Token *tok)
{
reportError(tok, "style", "cstyleCast", "C-style pointer casting");
@ -1051,3 +1063,8 @@ void CheckOther::nullPointerError(const Token *tok)
{
reportError(tok, "error", "nullPointer", "Possible null pointer dereference");
}
void CheckOther::zerodivWarning(const Token *tok)
{
reportError(tok, "style", "zerodivWarning", "Warning: Division with zero");
}

View File

@ -71,6 +71,7 @@ public:
checkOther.returnPointerToStackData();
checkOther.InvalidFunctionUsage();
checkOther.nullPointer();
checkOther.CheckZeroDivision();
}
// Casting
@ -112,6 +113,9 @@ public:
/** possible null pointer dereference */
void nullPointer();
/** Check zero division*/
void CheckZeroDivision();
protected:
void CheckVariableScope_LookupVar(const Token *tok1, const char varname[]);
@ -140,6 +144,7 @@ private:
void strPlusChar(const Token *tok);
void returnLocalVariable(const Token *tok);
void nullPointerError(const Token *tok);
void zerodivWarning(const Token *tok);
void getErrorMessages()
{
@ -161,6 +166,7 @@ private:
strPlusChar(0);
returnLocalVariable(0);
nullPointerError(0);
zerodivWarning(0);
}
};

View File

@ -35,6 +35,10 @@ private:
void run()
{
TEST_CASE(zeroDiv1);
TEST_CASE(zeroDiv2);
TEST_CASE(zeroDiv3);
TEST_CASE(delete1);
TEST_CASE(delete2);
@ -64,6 +68,9 @@ private:
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
// Simplify token list..
tokenizer.simplifyTokenList();
// Clear the error buffer..
errout.str("");
@ -71,11 +78,54 @@ private:
Settings settings;
CheckOther checkOther(&tokenizer, &settings, this);
checkOther.WarningRedundantCode();
checkOther.CheckZeroDivision();
}
void zeroDiv1()
{
check("void foo()\n"
"{\n"
" int a = 0;\n"
" double b = 1.;\n"
" cout<<b/a;\n"
"}");
ASSERT_EQUALS(std::string("[test.cpp:5]: (style) Warning: Division with zero\n"), errout.str());
}
void zeroDiv2()
{
check("void foo()\n"
"{\n"
" int sum = 0;\n"
" int n = 100;\n"
" for(int i = 0; i < n; i ++)\n"
" {\n"
" sum += i; \n"
" }\n"
" cout<<b/sum;\n"
"}\n");
ASSERT_EQUALS(std::string(""), errout.str());
}
void zeroDiv3()
{
check("int sum = 0;\n"
"void foo()\n"
"{\n"
" int n = 100;\n"
" cout<<b/sum;\n"
"}\n"
"}\n");
TODO_ASSERT_EQUALS(std::string("[test.cpp:5]: (style) Warning: Division with zero\n"), errout.str());
}
void delete1()
{
check("void foo()\n"