Menu

Memory leak in StrongPtr?

avav
2007-02-12
2013-04-08
  • avav

    avav - 2007-02-12

    Hi all,
    I find that there will be a leak "TwoRefCountInfo" if there are weak pointers exists in some cases. Consider the following code:

    void test(){
       StrongPtr<int, false> pWeakInt;
       {
          StrongPtr<int, true> pStrongInt(new int());
          pWeakInt = pStrongInt;
       }
    }

    When the program leaves the scope of test(), the pointee object (in this case, it's an int) will be deleted by DeletePolicy. But the counter "TwoRefCountInfo" won't be deleted!!!
    This is beacuse the pointer to pointee is zapped in the ~StrongPtr() when pStrongInt leaves it's scope. And then, when the last weak pointer(pWeakInt) leaves it's scope and ~StrongPtr() is called. Since the pointer is zapped, "p = GetPointer()" will be NULL and the program will never run to DP::Delete(p). ( See <Loki/StrongPtr.h>, line #929 )

    Although the counters will be released by SmallObjAllocator eventually, it's still kind of leak and the clean up only happens when program terminates.

     
    • Nobody/Anonymous

      Looks like to solve this problem won't be difficult:
      In ~StrongPtr(), move the statement "OP::ZapPointer();" to be in front of the statement "if ( p != 0 )".
      The result is like this:
              ~StrongPtr()
              {
                  if ( OP::Release( Strong ) )
                  {
                      T * p = GetPointer();
                      OP::ZapPointer();
                      if ( p != 0 )
                      {
                          DP::Delete( p );
                      }
                  }
              }

       
    • avav

      avav - 2007-02-13

      Outch, I just posted a reply without login. -_-

      Looks like to solve this problem won't be difficult:
      In ~StrongPtr(), move the statement "OP::ZapPointer();" to be in front of the statement "if ( p != 0 )".
      The result is like this:
      ~StrongPtr()
      {
      &nbspif ( OP::Release( Strong ) )
      &nbsp{
      &nbsp&nbspT * p = GetPointer();
      &nbsp&nbspOP::ZapPointer();
      &nbsp&nbspif ( p != 0 )
      &nbsp&nbsp&nbspDP::Delete( p );
      &nbsp}
      }

       
    • Peter Kuemmel

      Peter Kuemmel - 2007-02-25
       

Log in to post a comment.