Memory leak with Mat in convertTo-function

2019-03-01 08:09发布

问题:

I have some trouble with managing memory in my function. Valgrid says I'm having a memory leak after the convert-function. Could it be because of the data is not being properly released? I've tried to use temp-pointers, but my program either crashes or is not working properly. Have someone encountered this problem before?

this->images.push_back(new cv::Mat());                                                          //ID
cv::threshold(*this->images[MASK], *this->images[ID], 0.0, 1.0, cv::THRESH_BINARY);
this->images[ID]->convertTo(*this->images[ID], CV_32SC1);

This is the valgrid output:

==5663== 64,339,996 bytes in 1 blocks are possibly lost in loss record 380 of 380
==5663==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5663==    by 0x4E95117: cv::fastMalloc(unsigned long) (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663==    by 0x4F31F38: cv::Mat::create(int, int const*, int) (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663==    by 0x4F39CF9: cv::_OutputArray::create(cv::Size_<int>, int, int, bool, int) const (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663==    by 0x4EB9373: cv::Mat::convertTo(cv::_OutputArray const&, int, double, double) const (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663==    by 0x40D168: DataFrame::init() (DataFrame.cpp:68)
==5663==    by 0x40C943: DataFrame::DataFrame(char const*, LeafClassifier*) (DataFrame.cpp:31)
==5663==    by 0x414A19: DataHandler::loadFrame() (DataHandler.cpp:68)
==5663==    by 0x406680: main (main.cpp:58)

回答1:

please don't store pointers to Mat in your vector(or anywhere else !).

those things are refcounted internally, like smartpointers, and you're wrecking that by storing/copying pointers (a vector of pointers to smartpointers would sound silly anyway, no?).

use a plain vector<Mat>, trade some additional ~56 bytes per item against sound sleep tonight ;)