the Compartmented Robust Posix C++ Unit Test system

ASSERT_SCOPE_HEAP_LEAK_FREE

Assert that all heap objects allocated in the the block of code immediately following the macro, are also deallocated in the same block.

Used in: A test function body, the constructor or destructor of a fixture, or a function called from them. See TEST(name, ...).

Requirement: A code block follows immediately after.

The assertion succeeds if, and only if, all heap objects allocated in the code block following are also deallocated in the block, so that the objects on the heap are exactly the same before the code of block begins and after the code of block ends.

On success the test function continues without side effects.

On failure, the test is terminated with an error report. The report includes all heap objects allocated in the block of code that still exists after the destructors for the block of code have finished.

See also: VERIFY_SCOPE_HEAP_LEAK_FREE.

Example: The test program

     
     #include <crpcut.hpp>
     #include <string>
     
     TEST(heap_in_balance)
     {
       std::string before("a");
       ASSERT_SCOPE_HEAP_LEAK_FREE
       {
         std::string after("b");
       }
     }
     
     TEST(heap_imbalance)
     {
       std::string before("a");
       ASSERT_SCOPE_HEAP_LEAK_FREE
       {                           // This is not a memory leak, but it is reported
         std::string after("b");   // as such because the object allocated here is
         std::swap(before, after); // not released at the end of the block
       }
     }
     
     TEST(heap_leak)
     {
       char *p[5];
       ASSERT_SCOPE_HEAP_LEAK_FREE
       {
         int i;
         for (i = 0; i < 5; ++i)
           {
             p[i] = new char[i+1];
           }
         while (--i > 0)
           {
             delete[] p[i];
           }
       }
     }
     int main(int argc, char *argv[])
     {
       return crpcut::run(argc, argv);
     }

    

reports two failed test:


     FAILED: heap_imbalance
     phase="running"  --------------------------------------------------------------
     /home/bjorn/devel/crpcut/doc-src/samples/assert_scope_leak_free.cpp:43
     ASSERT_SCOPE_LEAK_FREE
     1 object
     
     26 bytes at 0x2b4dcd616c00 allocated with new
     -------------------------------------------------------------------------------
     ===============================================================================
     FAILED: heap_leak
     phase="running"  --------------------------------------------------------------
     /home/bjorn/devel/crpcut/doc-src/samples/assert_scope_leak_free.cpp:53
     ASSERT_SCOPE_LEAK_FREE
     1 object
     
     1 byte at 0x2b4dcd61ec10 allocated with new[]
     -------------------------------------------------------------------------------
     ===============================================================================
     Total 3 test cases selected
     UNTESTED : 0
     PASSED   : 1
     FAILED   : 2