Search code examples
c++shared-ptr

Memory leak using shared_ptr


Both code examples compile and run without problems. Using the second variant results in a memory leak. Any ideas why? Thanks in advance for any help.

Variant 1:

typedef boost::shared_ptr<ParameterTabelle> SpParameterTabelle;

struct ParTabSpalteData
{
      ParTabSpalteData(const SpParameterTabelle& tabelle, const string& id)
            :Tabelle(tabelle), Id(id)
      {

      }

      const SpParameterTabelle& Tabelle;
      string Id;
};

Variant 2:

struct ParTabSpalteData
{
      ParTabSpalteData(const SpParameterTabelle& tabelle, const string& id)
            :Id(id)
      {
            // causes memory leak
            Tabelle2 = tabelle;
      }

      SpParameterTabelle Tabelle2;
      string Id;
};

Solution

  • Have you checked, that you do not have cyclic shared pointer references?

    For example:

    class A {
      public: shared_ptr<A> x;
    };
    
    shared_ptr<A> a1(new A());
    shared_ptr<A> a2(new A());
    a1->x = a2;
    a2->x = a1;
    

    Here a1 and a2 will never be released, because they have pointers to each other which keeps them alive.

    So in your case check if SpParameterTabelle has a reference on ParTabSpalteData or if there is another possibility to get a cyclic reference.