【发布时间】:2011-08-27 05:46:57
【问题描述】:
我有这门课
class LayoutEntry
{
unsigned int id_;
string name_;
bool isInput_;
};
复制构造函数如下所示:
LayoutEntry(const LayoutEntry &other)
: id_(other.id_),
name_(other.name_),
isInput_(other.isInput_)
{
}
这个类的对象被放在另一个类的映射中
class DataLayoutDescription
{
unsigned int sz_;
set<LayoutEntry, SortByOffset> impl;
// HERE!!!
map<unsigned int, LayoutEntry> mapById;
这个类的拷贝构造函数如下所示:
DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
:sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}
现在的问题:
- 当像打印一样运行时,每个 LayoutEntry 都会出现内存泄漏
- 如果我在 DataLayoutDescription 的复制构造函数中删除
mapById(other.mapById)则没有 memleak - 如果我删除
name_(other.name_),,内存泄漏也消失了
为什么?
编辑
对于测试,我在最后使用 BOOST::UnitTest 我得到一个内存泄漏转储
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.
可能的原因? 我使用此方法将 DataLayoutDescription 保存在共享内存区域中
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;
}
}
我取消引用迭代器 ant 将其副本存储在位于共享内存区域的数组中。有什么不对?共享内存在退出时被删除。
进一步追踪 LayoutEntry 类放置在共享内存区域内的数组中,并包含一个字符串。内存泄漏的原因是字符串被调整大小。因此它在堆上分配了更多的内存。现在我猜这个内存不会被释放,因为原始内存位于共享内存中。这可能是原因吗?接下来我将尝试删除字符串并将其替换为固定长度的 char 数组。
...几分钟后
就是这样。用固定的 char 数组替换字符串后,内存泄漏消失了。希望这对某人有所帮助。
【问题讨论】:
-
这看起来很完美。是什么让你觉得这里有内存泄漏?
-
您发布的代码中没有明显的内存泄漏。为什么你认为你有一个?
-
@schoetbi:如果您运行该程序两次,该转储中的分配编号是否相同?
-
@sharptooth:是的,如果我不更改代码,分配数字将保持不变
-
@nos: DataLayoutDescription 在堆栈上
标签: c++ memory-leaks