【发布时间】:2012-05-06 08:00:40
【问题描述】:
我正在使用 mapPixel 的概念创建一个地图网格(一个 2D 离散点),一个类:
class MapPixel
{
friend class Map;
protected:
int x;
int y;
float height;
float vegetation;
std::vector<const MapPixel*> neib;
...methods declaration, default constructor/destructor
其中 neib 是指向其他 MapPixels 的指针列表,与 then 相邻。
我用的是方法
void MapPixel::addNeib(const MapPixel* neib_)
{
neib.push_back(neib_);
}
添加指向 neiber 像素的指针以构建图形(由于边界的 neib 比中心像素少,因此此列表取决于大小)。
我的程序是有一个带有成员的类 Map
MapPixel **pixels;
在构造函数 Map::Map() 中使用
pixels = new MapPixel*[width];
for (int i = 0; i < width; i++)
pixels[i] = new MapPixel[height];
我使用 MapPixel::addNode() 方法构建网络(例如)
pixels[i][j].addNeib(&pixels[i][j+1]);
在 Map::~Map() 中,我按相反的顺序删除 MapPixel(不删除 neib 以避免双重释放):
for (int i = 0; i < width; i++)
delete pixels[i];
delete pixels;
Valgrind 说有几个像这样的大内存泄漏:
2,509,088 bytes in 39,205 blocks are possibly lost in loss record 4,071 of 4,071
in MapPixel::addNeib(MapPixel const*) in Source/mappixel.cpp:52
1: malloc in vg_replace_malloc.c:266
2: operator new(unsigned long) in /usr/lib/libstdc++.6.0.9.dylib
3: __gnu_cxx::new_allocator<MapPixel const*>::allocate(unsigned long, void const*) in ...
4: std::_Vector_base<MapPixel const*, std::allocator<MapPixel const*> >::_M_allocate(unsigned long) in stl_vector.h:131
5: std::vector<MapPixel const*, std::allocator<MapPixel const*> >::_M_insert_aux(__gnu_cxx::__normal_iterator<MapPixel const**, std::vector<MapPixel const*, std::allocator<MapPixel const*> > >, MapPixel const* const&) in vector.tcc:271
6: std::vector<MapPixel const*, std::allocator<MapPixel const*> >::push_back(MapPixel const* const&) in stl_vector.h:608
7: MapPixel::addNeib(MapPixel const*) in mappixel.cpp:52
与第 52 行有关:
neib.push_back(neib_);
有人明白吗?现在我对是否可以使用 std::vector 来构建像素的 neibs 失去信心。
【问题讨论】:
-
在可能的内存泄漏问题中,您应该告诉我们您如何分配(新)和如何释放(删除)...这里缺少一部分。例如。你按相反的顺序删除MaxPixel,ok;但你是像素本身吗?我想答案是肯定的,并且给定的答案适用。不过,最好有完整的新/删除代码来查看!
-
添加了删除代码。我说这不是因为 Valgrind 不会抱怨新像素/新像素 [i],这就是为什么我认为问题不存在。
-
不应该是
delete[]吗? -
我对 C++ 很生疏,我怀疑
delete[]是否在元素上调用析构函数,确实如此,但这里我们有普通指针,而不是 MapPixel 对象或对它们的引用,所以看起来那:你释放了你动态创建的 MapPixel 对象,但没有正确释放动态创建的指针数组(指向此类对象)。
标签: c++ memory-leaks valgrind