Memory leak using shared_ptr
Both code examples compile and run without issue. Using the second option leads to a memory leak. Any ideas why? Thanks in advance for any help.
Option 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;
};
Option 2:
struct ParTabSpalteData
{
ParTabSpalteData(const SpParameterTabelle& tabelle, const string& id)
:Id(id)
{
// causes memory leak
Tabelle2 = tabelle;
}
SpParameterTabelle Tabelle2;
string Id;
};
a source to share
Have you verified that you have no circular references to links?
For instance:
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 that store them.
So, in your case, check if there is a SpParameterTabelle
reference to ParTabSpalteData
or there is another possibility to get a circular reference.
a source to share
Note that passing a smart pointer as const SpParameterTabelle & tabelle does not prevent you from modifying the pointee object.
Have you tried skipping the immediate smart pointer since
struct ParTabSpalteData
{
ParTabSpalteData(SpParameterTabelle tabelle, const string& id)
:Tabelle2(tabelle), Id(id)
{
}
SpParameterTabelle Tabelle2;
string Id;
};
a source to share
Output something to the ParameterTabelle destructor (trace / file) or set a breakpoint there. Isn't this really getting called twice?
I recently upgraded my VS2005 project to VS2010 and suddenly VS2010 reported a memory leak in boost :: lexical_cast. And not all of them, only one module on the same line - there were even other lexical_cast of the same type / other types in this file.
Even local memory health tests reported this as a memory leak (for debug mode only):
void run_stream_tests(std::ofstream& out)
{
#ifdef _DEBUG
CMemoryState preState;
preState.Checkpoint();
#endif
{
...your code...
}
#ifdef _DEBUG
CMemoryState postState;
postState.Checkpoint();
CMemoryState diffState;
if( diffState.Difference( preState, postState ) )
{
TRACE("Memory leaked!\n");
preState.DumpAllObjectsSince();
}
#endif
}
So this could also be a VS2010 / VS2008 issue.
a source to share