Skip to content

Commit eb3bf57

Browse files
committed
Avoid divisions by zero when simplifying numeric calculations.
1 parent 09f4d37 commit eb3bf57

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

lib/templatesimplifier.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,7 @@ bool TemplateSimplifier::simplifyNumericCalculations(Token *tok)
766766
while (tok->tokAt(4) && tok->next()->isNumber() && tok->tokAt(3)->isNumber()) { // %any% %num% %any% %num% %any%
767767
const Token* op = tok->tokAt(2);
768768
const Token* after = tok->tokAt(4);
769-
if (Token::Match(tok, "* %num% /") && tok->next()->str() == MathLib::multiply(tok->strAt(3), MathLib::divide(tok->next()->str(), tok->strAt(3)))) {
769+
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)))) {
770770
// Division where result is a whole number
771771
} else if (!((op->str() == "*" && (isLowerThanMulDiv(tok) || tok->str() == "*") && isLowerEqualThanMulDiv(after)) || // associative
772772
(Token::Match(op, "[/%]") && isLowerThanMulDiv(tok) && isLowerEqualThanMulDiv(after)) || // NOT associative

test/testother.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class TestOther : public TestFixture {
4242
TEST_CASE(zeroDiv4);
4343
TEST_CASE(zeroDiv5);
4444
TEST_CASE(zeroDiv6);
45+
TEST_CASE(zeroDiv7); // #4930
4546

4647
TEST_CASE(nanInArithmeticExpression);
4748

@@ -414,6 +415,15 @@ class TestOther : public TestFixture {
414415
"} } }");
415416
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout.str());
416417
}
418+
419+
void zeroDiv7() {
420+
check("void f() {\n"
421+
" int a = 1/2*3/0;\n"
422+
" int b = 1/2*3%0;\n"
423+
"}");
424+
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n"
425+
"[test.cpp:3]: (error) Division by zero.\n", errout.str());
426+
}
417427

418428
void nanInArithmeticExpression() {
419429
check("void f()\n"

0 commit comments

Comments
 (0)