Ask Your Question
4

Why doesn't OpenCV complain when you address out of bounds?

asked 2013-04-18 01:22:35 -0600

Rafajafar gravatar image

updated 2013-04-18 02:07:16 -0600

I just spent half a day debugging a very large problem for a memory issue. The memory issue was weird for a lot of reasons, to the point that guys on #c++ where saying, "I dunno man, that's ... weird."

What was happening, I found after a lot of valgrind and gdb, is that I was able to address outside of the space of Mat.

Here's the code in question that caused the problem:

    vector< Mat > dripped_img, line_img, pixel;
    for(int i = 0; i < TESTS ; i++){
            dripped_img.push_back(src_img);
            transpose(src_img, src_img);
            line_img.push_back(Mat::zeros(src_img.cols, 1, CV_8UC3));
            pixel.push_back(Mat::zeros(1,1, CV_8UC3));
    }

See what might cause the problem? Here's the simple fix I was looking for:

    vector< Mat > dripped_img, line_img, pixel;
    for(int i = 0; i < TESTS ; i++){
            dripped_img.push_back(src_img);
            line_img.push_back(Mat::zeros(src_img.cols, 1, CV_8UC3));
            pixel.push_back(Mat::zeros(1,1, CV_8UC3));
            transpose(src_img, src_img);
    }

Might be a bit ambiguous, but dripped_img and line_img are related. This means that when I iterate through dripped_img and stored into line_img, if those columns don't match, whoops.

Total logic error on my part, I know. However, what was weird was how little error reporting happened when I did this. What I saw the error as was a function which segfaulted on return. I'm of the mind you should be able to direct-index past the bounds of the Matrix, though.

Is there a reason why this behaviour is allowed in OpenCV?

EDIT: I said "direct-index" makes sense. But I was using Mat.at(). Maybe that needs some checking.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2013-04-19 09:44:01 -0600

Guanta gravatar image

OpenCV is more orientated in speed, i.e. there is no array-index-out-of-bounds-exception like it is in Java or if you use .at() by a vector. Since iterating over huge matrix is already time consuming, these checks would make it worse. You can surpass this problem by writing your own at() method which checks your boundaries, or use MatIterators (then you are independent of cols/rows).

edit flag offensive delete link more
0

answered 2015-09-01 12:08:55 -0600

namanspace gravatar image

wow! what an answer, Guanta, this is a hidden gem to be honest.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-04-18 01:22:35 -0600

Seen: 2,470 times

Last updated: Apr 19 '13