问题
I'm simply trying to write to a matrix of a given size. When I run this program in Valgrind, I get memory errors as shown below:
main.cpp:
#include <iostream>
#include <opencv2/opencv.hpp>
int main()
{
cv::Mat m = cv::Mat::zeros(cv::Size(59, 9), CV_32SC1);
m.at<int>(9, 4) = 1;
}
Compiling instructions:
g++ -I/usr/local/include/opencv -I/usr/local/include/opencv2 -L/usr/local/lib/ -g -o binary main.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_stitching
Finally run Valgrind:
valgrind ./binary
It returns this message on my machine:
==98408== Invalid write of size 4
==98408== at 0x1000017F8: main (main.cpp:7)
==98408== Address 0x10dd202cc is 4 bytes after a block of size 2,152 alloc'd
==98408== at 0x100009EAB: malloc (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==98408== by 0x10001D1E6: cv::fastMalloc(unsigned long) (in /usr/local/Cellar/opencv/2.4.12/lib/libopencv_core.2.4.12.dylib)
==98408== by 0x1000F4C77: cv::Mat::create(int, int const*, int) (in /usr/local/Cellar/opencv/2.4.12/lib/libopencv_core.2.4.12.dylib)
==98408== by 0x1000F0A51: cv::MatOp_Initializer::assign(cv::MatExpr const&, cv::Mat&, int) const (in /usr/local/Cellar/opencv/2.4.12/lib/libopencv_core.2.4.12.dylib)
==98408== by 0x1000018FB: cv::MatExpr::operator cv::Mat() const (mat.hpp:1227)
==98408== by 0x1000017BC: main (main.cpp:6)
These are the specifications of my machine:
Apple LLVM version 7.0.0 (clang-700.1.76)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
homebrew/science/opencv 2.4.12
回答1:
You seem to have the dimensions of your matrix mixed up. You construct a matrix with 59 columns and 9 rows, and access the 10th row and 4th column:
cv::Size(width,height); // size specification
m.at<int>(y,x); // access
So row 9 is out of range. Either swap the dimensions, or the indices!
回答2:
You're accessing the matrix out of bounds.
cv::Mat m = cv::Mat::zeros(cv::Size(59, 9), CV_32SC1);
will create a matrix with 9x59 matrix (9 rows, 59 columns). And you are accessing the 10th row.
来源:https://stackoverflow.com/questions/33824695/why-am-i-getting-memory-errors-when-accessing-this-matrix-in-opencv