[英]Why am I getting memory errors when accessing this matrix in OpenCV?
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: 当我在Valgrind中运行此程序时,出现内存错误,如下所示:
main.cpp: 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:
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
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). 将创建一个9x59矩阵(9行,59列)的矩阵。 And you are accessing the 10th row. 你正在访问第10行。
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: 构造一个包含59列和9行的矩阵,并访问第10行和第4列:
cv::Size(width,height); // size specification
m.at<int>(y,x); // access
So row 9 is out of range. 所以第9行超出了范围。 Either swap the dimensions, or the indices! 交换尺寸或指数!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.