My memory is getting full fairly quick once using the next piece of code. Valgrind shows a memory leak, but everything is allocated on stack and (supposed to be) freed once the function ends.
void mult_run_time(int rows, int cols)
{
Mat matrix(rows,cols,CV_32SC1);
Mat row_vec(cols,1,CV_32SC1);
/* initialize vector and matrix */
for (int col = 0; col < cols; ++col)
{
for (int row = 0; row < rows; ++row)
{
matrix.at<unsigned long>(row,col) = rand() % ULONG_MAX;
}
row_vec.at<unsigned long>(1,col) = rand() % ULONG_MAX;
}
/* end initialization of vector and matrix*/
matrix*row_vec;
}
int main()
{
for (int row = 0; row < 20; ++row)
{
for (int col = 0; col < 20; ++col)
{
mult_run_time(row,col);
}
}
return 0;
}
Valgrind shows that there is a memory leak in line Mat row_vec(cols,1,CV_32CS1):
==9201== 24,320 bytes in 380 blocks are definitely lost in loss record 50 of 50
==9201== at 0x4026864: malloc (vg_replace_malloc.c:236)
==9201== by 0x40C0A8B: cv::fastMalloc(unsigned int) (in /usr/local/lib/libopencv_core.so.2.3.1)
==9201== by 0x41914E3: cv::Mat::create(int, int const*, int) (in /usr/local/lib/libopencv_core.so.2.3.1)
==9201== by 0x8048BE4: cv::Mat::create(int, int, int) (mat.hpp:368)
==9201== by 0x8048B2A: cv::Mat::Mat(int, int, int) (mat.hpp:68)
==9201== by 0x80488B0: mult_run_time(int, int) (mat_by_vec_mult.cpp:26)
==9201== by 0x80489F5: main (mat_by_vec_mult.cpp:59)
Is it a known bug in OpenCV or am I missing something?
There is no use in using unsigned long at
because rand() returns an intenger anyways, so there is no gain in the total range, so use unsigned int instead.
In the line:
you are accessing an outside range index. In c++, vectors starts from 0 and not 1. And the matrix are stored row-by-row in opencv. You are acessing unallocated memory area, thats probably the reason why valgrind is finding memory leaks. Use:
I presume that you are not compiling your program in Debug Mode because if it were the case, opencv uses an assertion before accessing an index to make sure you are inside the total range of the vector, if you were compiling in debug mode, your program would throw an assertion failure during the execution of your code, what makes easier to track this kind of mistakes. I recomend you to start prototyping your code in debug mode.