Boost logo

Boost Users :

Subject: [Boost-users] shared_ptr memory leak
From: gast128 (gast128_at_[hidden])
Date: 2009-02-26 15:58:00


Dear all,

we managed to create a shared_ptr memory leak, without making a cycle. Granted
it is highly controversial case. One has to make call in the destructor of the
owned object which loops back to the point of assignment.

Is this something for the documentation, or may this indeed be flagged as
a 'nut' case.

Code below is a simplified example, the production case was with some kind of
change manager which notification bounced back to the point of assignment. One
has to split out header and cpp to get it compilable.

void TestSharedPtrLeak()
{
   //make the leak
   KTestBoostHlpSpLeakParent leak;
   leak.Reset(false);
}

//ktestboosthlpspleakparent.h
struct KTestBoostHlpSpLeakParent
{
   KTestBoostHlpSpLeakParent();
   
   void Reset(bool b);
   
   boost::shared_ptr<KTestBoostHlpSpLeak> m_ptr;
};

//ktestboosthlpspleakparent.cpp
KTestBoostHlpSpLeakParent::KTestBoostHlpSpLeakParent()
{
   Reset(true);
}

void KTestBoostHlpSpLeakParent::Reset(bool b)
{
   boost::shared_ptr<KTestBoostHlpSpLeak> ptr(new KTestBoostHlpSpLeak(this,
b));
   
   m_ptr = ptr;
   //m_ptr.swap(ptr); //would solve it btw
}

//ktestboosthlpspleak.h
struct KTestBoostHlpSpLeak
{
   KTestBoostHlpSpLeak(KTestBoostHlpSpLeakParent* p, bool b);
   ~KTestBoostHlpSpLeak();
   
public:
   KTestBoostHlpSpLeakParent* m_p;
   bool m_b;
};

//ktestboosthlpspleak.cpp
KTestBoostHlpSpLeak::KTestBoostHlpSpLeak(KTestBoostHlpSpLeakParent* p, bool b)
 : m_p(p)
 , m_b(b)
{
}

KTestBoostHlpSpLeak::~KTestBoostHlpSpLeak()
{
   if (m_b)
   {
      //recursive call
      m_p->Reset(false);
   }
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net