diff --git a/lib/checkexceptionsafety.cpp b/lib/checkexceptionsafety.cpp index 946c99727..3aefc1433 100644 --- a/lib/checkexceptionsafety.cpp +++ b/lib/checkexceptionsafety.cpp @@ -166,4 +166,31 @@ void CheckExceptionSafety::unsafeNew() } } } + + // allocating multiple local variables.. + std::set localVars; + unsigned int countNew = 0; + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + { + if (tok->str() == "{" || tok->str() == "}") + { + localVars.clear(); + countNew = 0; + } + + if (Token::Match(tok, "[;{}] %type% * %var% ;")) + { + tok = tok->tokAt(3); + if (tok->varId()) + localVars.insert(tok->varId()); + } + + if (Token::Match(tok, "; %var% = new")) + { + if (tok->next()->varId() && localVars.find(tok->next()->varId()) != localVars.end()) + ++countNew; + if (countNew >= 2) + unsafeNewError(tok->next()); + } + } } diff --git a/lib/checkexceptionsafety.h b/lib/checkexceptionsafety.h index cbee704e4..d8e288da9 100644 --- a/lib/checkexceptionsafety.h +++ b/lib/checkexceptionsafety.h @@ -46,6 +46,7 @@ public: { CheckExceptionSafety checkExceptionSafety(tokenizer, settings, errorLogger); checkExceptionSafety.destructors(); + checkExceptionSafety.unsafeNew(); } diff --git a/test/testexceptionsafety.cpp b/test/testexceptionsafety.cpp index 7d72d621d..82e6981b0 100644 --- a/test/testexceptionsafety.cpp +++ b/test/testexceptionsafety.cpp @@ -83,6 +83,13 @@ private: " b = new B;\n" "}\n"); ASSERT_EQUALS("[test.cpp:4]: (style) Exception safety: unsafe use of 'new'\n", errout.str()); + + check("void a()\n" + "{\n" + " A *a1 = new A;\n" + " A *a2 = new A;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4]: (style) Exception safety: unsafe use of 'new'\n", errout.str()); } };