exc_bad_access when using Mat in OpenCV although it looks like my indexes are correct

asked 2013-11-08 09:01:08 -0600

Ilan gravatar image

I develop some algorithm on Mac using Xcode 5 and OpenCV. I do it as C++.

I define matrix:

Mat src;
int cols = 560;
int rows = 260;
src.create( rows, cols, DataType<double>::type);

In the code I have a loop looks like this:

for (int i=0; i<src.rows; i++) {
        const double* srcIterator = src.ptr<double>(i);
        for (int j=0; j<src.cols; j++) {
            double temp = srcIterator[j];

I read the function that has this loop for every frame I read. Most of the times it runs correctly (it is running in endless loop and it always ok).

In some runs I get exc_bad_access error. When it happened it happened for the first frame. The error is on the line: double temp = srcIterator[j];

When it happened j is much bellow 560 and alway above 500, but each time it has a deferent value.

I thought may be I mix the cols and rows but if it was right I would get this error when j was 260 (the size of rows).

Please, Anyone has any guess what can it be?

edit retag flag offensive close merge delete


nothing wrong with the code, you show here, but it's probably not the exact thing you're using, right ?

berak gravatar imageberak ( 2013-11-08 09:28:01 -0600 )edit

The code is copy paste from my code. The only changes are: 1. The number of rows and cols are calculated and not constant numbers (but I run on one example so this are the numbers I get). 2. The loops are in a function and the Mat is created and filled with values out side this function. The Mat src transferred as parameter to the function with the loop. 3. There is a deferent purpose for this function. But because I get this error in the original loop, I comment all the function and did in the function only the code as in my question. So the bottom line is that the exact code I use. Amazing!!! Isn't it?

Ilan gravatar imageIlan ( 2013-11-08 10:01:58 -0600 )edit

was more guessing from the useless temp++ .

exc_bad_access comes from your os, right ? sounds more like UB in some completely different place in your code

berak gravatar imageberak ( 2013-11-08 10:21:44 -0600 )edit

The useless temp++ is only to not get warning of assigning value to unused variable. The exc_bad_access I get it on run time. I don't understand, what is it 'UB'?

Ilan gravatar imageIlan ( 2013-11-11 10:28:54 -0600 )edit

UB = Undefined Behaviour. like, when you got a buffer overrun in a different location in your code.

berak gravatar imageberak ( 2013-11-11 10:40:01 -0600 )edit