[英]memory leak (Valgrind) on a grid of points
我正在使用class類mapPixel的概念創建地圖網格(二維離散點):
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是與之相鄰的指向其他MapPixel的指針的列表。
我正在使用方法
void MapPixel::addNeib(const MapPixel* neib_)
{
neib.push_back(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以避免double free):
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構建像素的近景點失去了信心。
請注意,valgrind表示“ 可能丟失”,而不是“ 絕對丟失”。 區別很重要。 具體含義請參見此處 。
該錯誤與vector<>
實現代碼分配的塊有關,最有可能隨着vector
增長而調整包含元素的內存塊的大小。 如果您正在分配MapPixel
實例而忘記釋放它們,則可能會得到這些,因為包含vector
將無法釋放其內存,但同時也會出現有關您自己的代碼的錯誤。
除非! 當釋放pixels
數組時,是否使用delete[]
或delete
?
更新:您正在使用delete
。 您需要使用delete[]
。 這確實是內存泄漏。 您使用new[]
分配的所有內容都必須使用delete[]
釋放,否則,僅對第一個元素調用適當的析構函數(甚至由編譯器自動生成的析構函數)。
正如已經提到的其他答案一樣,內存泄漏很可能是由錯誤的delete
運算符引起的。 在構造函數中,使用運算符new []創建一個數組數組:
pixels = new MapPixel*[width];
for (int i = 0; i < width; i++)
pixels[i] = new MapPixel[height];
您需要使用相應的array-delete 運算符delete []釋放陣列的內存:
for (int i = 0; i < width; i++)
delete [] pixels[i];
delete [] pixels;
但是,我建議您使用嵌套的std::vector
代替像素矩陣。 這樣,您可以免費獲得內存管理。
std::vector<std::vector<MapPixel> > pixels;
// in constructor something like:
pixels.resize(width, std::vector<MapPixel>(height));
// nothing to do in destructor
對於您的鄰居,我不會使用std :: vector,而是使用普通的MapPixel *neib[8];
(假設摩爾鄰里)或更確切地說std::array<MapPixel*, 8> neib;
。 但是我不知道您可能對此項目還有其他要求。
除了內存管理之外,使用STL容器還為您帶來其他好處,例如,方便的成員函數,它們不會衰減到指針,僅舉幾例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.