From 21e0639443653edd9a863a692a389715247e06df Mon Sep 17 00:00:00 2001 From: Slava Semushin Date: Fri, 5 Jun 2009 11:03:48 +0700 Subject: [PATCH] Fixed ticket #360 (Teach about new(std::nothrow) form) http://apps.sourceforge.net/trac/cppcheck/ticket/360 --- src/checkmemoryleak.cpp | 8 ++++++-- test/testmemleak.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/checkmemoryleak.cpp b/src/checkmemoryleak.cpp index f1359768c..95a3e447c 100644 --- a/src/checkmemoryleak.cpp +++ b/src/checkmemoryleak.cpp @@ -103,10 +103,14 @@ CheckMemoryLeakClass::AllocType CheckMemoryLeakClass::GetAllocationType(const To return gMalloc; } - if (Token::Match(tok2, "new %type% [;()]")) + if (Token::Match(tok2, "new %type% [;()]") || + Token::Match(tok2, "new ( std :: nothrow ) %type% [;()]") || + Token::Match(tok2, "new ( nothrow ) %type% [;()]")) return New; - if (Token::Match(tok2, "new %type% [")) + if (Token::Match(tok2, "new %type% [") || + Token::Match(tok2, "new ( std :: nothrow ) %type% [") || + Token::Match(tok2, "new ( nothrow ) %type% [")) return NewArray; if (Token::Match(tok2, "fopen|tmpfile (")) diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp index 2ddb1429d..82f3448d0 100644 --- a/test/testmemleak.cpp +++ b/test/testmemleak.cpp @@ -69,6 +69,7 @@ private: TEST_CASE(simple8); TEST_CASE(simple9); // Bug 2435468 - member function "free" TEST_CASE(simple10); // fclose in a if condition + TEST_CASE(new_nothrow); TEST_CASE(alloc_alloc_1); @@ -340,8 +341,48 @@ private: ASSERT_EQUALS("", errout.str()); } + void new_nothrow() + { + check("void f()\n" + "{\n" + " int *p = new(std::nothrow) int;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: p\n", errout.str()); + check("void f()\n" + "{\n" + " using std::nothrow;\n" + " int *p = new(nothrow) int;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: p\n", errout.str()); + check("void f()\n" + "{\n" + " int *p = new(std::nothrow) int[10];\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: p\n", errout.str()); + + check("void f()\n" + "{\n" + " using namespace std;\n" + " int *p = new(nothrow) int[10];\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: p\n", errout.str()); + + check("void f()\n" + "{\n" + " int *p = new(std::nothrow) int;\n" + " delete [] p;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4]: (error) Mismatching allocation and deallocation: p\n", errout.str()); + + check("void f()\n" + "{\n" + " int *p = new(std::nothrow) int[10];\n" + " delete p;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4]: (error) Mismatching allocation and deallocation: p\n", errout.str()); + } void alloc_alloc_1() {