Segmentation fault when doing arithmetic operations on cv::Mat
I use some opencv functions in one lib that I build as a shared object (libfoo.so)
In order to have only one .so file loaded in runtime, I use opencv as a static lib (libopencv_*.a) linked in libfoo.so.
Inside libfoo.so I have one static object from a class (Bar), and in the constructor I do some simple cv::Mat operations like:
Bar::Bar(){
barMat = cv::Mat::zeros(...);
barMat += 1;
}
...
static Bar b;
The problem is that I always get a segfault when it reaches the += (or any other arithmetic operation with Mat).
The following is the smallest example I came up with to reproduce the fault:
#include <opencv2/opencv.hpp>
class Bug {
public:
Bug() {
cv::Mat M = cv::Mat::zeros(3,3,CV_8U);
M += 10;
}
};
static Bug b;
int main(int argc, char** argv){}
Compile with
$ g++ bug.cpp `pkg-config --cflags --libs opencv`
And run
$ ./a.out
Segmentation fault (core dumped)
I already checked another question that seems to be related, but none of the proposed fixes solve my case: http://answers.opencv.org/question/4072/initializing-static-cvmat-with-cvmatzeros-causes/ https://github.com/Itseez/opencv/pull/2558
I compiled OpenCV from 2.4.9 tar.
Can anyone help?
I think the corresponding issue explains that it was fixed in version 2.4.10. You can also have a look at the github repo and see the differences between the tags.
@boaz001 I already tried with the fix proposed for this issue, but it does not solve. I also added some debug msgs in the opencv code, and my program is not breaking inside the functions changed in the pull request: https://github.com/Itseez/opencv/pull/2558
Can you debug?You can add -ggdb to the compiler options and start gdb with gdb a.out , then type run and see what happens.
Sure! The output is here: http://pastebin.com/FzJZBhJZ I also included a backtrace from gdb.
boaz001 I found that arithm_op was trying to access one InputArray that was a
noArray()
. And since the noArray function returns a static object, it may not be initialized. My workaround was to change the definition of _none in modules/core/src/matrix.cpp:The define was used to avoid interferences with other code that may be using the _none object. (And to avoid the need to change that code)
I am writing this in the comment because I cannot answer my own question yet. (only tomorrow)