I have this class
class LayoutEntry
{
unsigned int id_;
string name_;
bool isInput_;
};
The copy constructor looks like this:
LayoutEntry(const LayoutEntry &other)
: id_(other.id_),
name_(other.name_),
isInput_(other.isInput_)
{
}
Objects of this class are put inside a map within another class
class DataLayoutDescription
{
unsigned int sz_;
set<LayoutEntry, SortByOffset> impl;
// HERE!!!
map<unsigned int, LayoutEntry> mapById;
The copy constructor of this class looks like this:
DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
:sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}
Now the question:
- I Get a memory leak for each LayoutEntry when run like printed
- If I remove
mapById(other.mapById)in the copy constructor of DataLayoutDescription then there is no memleak - If I remove
name_(other.name_),The memory leaks are also gone
Why?
EDIT
For Testing I use BOOST::UnitTest at the end I get a memory leak dump
C:\wc\05_EAPGit\Debug>EapLibTest.exe --run-test=SharedVectorTest
Running 7 test cases...
*** No errors detected
Detected memory leaks!
Dumping objects ->
{1378} normal block at 0x005815C0, 16 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1377} normal block at 0x00581580, 16 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1376} normal block at 0x00581540, 16 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
Possible Reason? I persist the DataLayoutDescription in a shared memory area using this method
void DataLayoutDescription::Save(LayoutEntry *les, unsigned int maxEntries) const
{
int n = std::max(impl.size(), maxEntries);
int i = 0;
for (DataLayoutDescription::iterator it = begin(); it != end(); ++it)
{
les[i] = *it; // Source of memory leak here???
++i;
}
}
I dereference the iterator ant store a copy of this in the array that is located in the shared memory region. Is there something wrong? The shared memory is deleted on exit.
Furhter Trackdown The class LayoutEntry is placed in an array within a shared memory area and contains a string. The reason for the memory leak is that the string gets resized. Thus it allocates more memory on the heap. Now I guess that this memroy will not be freed since the original memory is located in the shared memory. Could this be the reason? Next thing I will try to remove the string and replace it with an char array of fixed length.
... after several minutes
This was it. After replacing the string with a fixed array of char the memory leak dissapeared. Hope this helps someone.