From 4059a2ad05364baed43ea9ce52732b93028d03f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 28 Mar 2009 07:49:47 +0100 Subject: [PATCH] added check for zero division. The code was written by Nguyen Duong Tuan --- src/checkother.cpp | 17 ++++++++++++++++ src/checkother.h | 6 ++++++ test/testother.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/src/checkother.cpp b/src/checkother.cpp index e1fe09b72..a3643ac05 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -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"); +} diff --git a/src/checkother.h b/src/checkother.h index f17dd1163..b7313d4ac 100644 --- a/src/checkother.h +++ b/src/checkother.h @@ -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); } }; diff --git a/test/testother.cpp b/test/testother.cpp index 4d9fbd63e..54ccf1f87 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -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<