Avoid divisions by zero when simplifying numeric calculations.

This commit is contained in:
Simon Martin 2013-07-28 12:32:18 +02:00
parent 09f4d3732a
commit eb3bf571be
2 changed files with 11 additions and 1 deletions

View File

@ -766,7 +766,7 @@ bool TemplateSimplifier::simplifyNumericCalculations(Token *tok)
while (tok->tokAt(4) && tok->next()->isNumber() && tok->tokAt(3)->isNumber()) { // %any% %num% %any% %num% %any%
const Token* op = tok->tokAt(2);
const Token* after = tok->tokAt(4);
if (Token::Match(tok, "* %num% /") && tok->next()->str() == MathLib::multiply(tok->strAt(3), MathLib::divide(tok->next()->str(), tok->strAt(3)))) {
if (Token::Match(tok, "* %num% /") && (tok->strAt(3) != "0") && tok->next()->str() == MathLib::multiply(tok->strAt(3), MathLib::divide(tok->next()->str(), tok->strAt(3)))) {
// Division where result is a whole number
} else if (!((op->str() == "*" && (isLowerThanMulDiv(tok) || tok->str() == "*") && isLowerEqualThanMulDiv(after)) || // associative
(Token::Match(op, "[/%]") && isLowerThanMulDiv(tok) && isLowerEqualThanMulDiv(after)) || // NOT associative

View File

@ -42,6 +42,7 @@ private:
TEST_CASE(zeroDiv4);
TEST_CASE(zeroDiv5);
TEST_CASE(zeroDiv6);
TEST_CASE(zeroDiv7); // #4930
TEST_CASE(nanInArithmeticExpression);
@ -414,6 +415,15 @@ private:
"} } }");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout.str());
}
void zeroDiv7() {
check("void f() {\n"
" int a = 1/2*3/0;\n"
" int b = 1/2*3%0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n"
"[test.cpp:3]: (error) Division by zero.\n", errout.str());
}
void nanInArithmeticExpression() {
check("void f()\n"