I don't understand why I get this error - malloc(): memory corruption: 0xb6ea46a5 ***

asked 2016-05-14 16:08:49 -0600

sohail gravatar image

I am working on connected component labeling in an image using opencv. The following is my code block which does that

`

Mat twopass(Mat img)
{
  int row=img.rows;
  int col=img.cols;
  int wd,ht;
  Mat sto=img;  
  wd=(col/2)+1;
  ht=row;
  vector<int> ct(1,wd*ht);

  char x=1;
  cout<<"here0\n";

  for(int i=1;i<img.rows-1;i++)
  {
      for(int j=1;j<img.cols-1;j++)
      {
         if(img.at<uchar>(i,j)==255)
         {
           if(j==0||img.at<uchar>(i,j-1)==255)
             sto.at<uchar>(i,j)=x;
           else
           {
             x++;
             sto.at<uchar>(i,j)=x;}
           }
         }
     }

     cout<<"here1\n";
     //second pass
     for (int i=1;i<img.rows-1;i++)
     {
         for (int j=1;j<img.cols-1;j++)
         {
             if(sto.at<uchar>(i,j)!=0)
             {
                 if(j!=0)
                 {
                   if(sto.at<uchar>(i-1,j)!=0)
                     sto.at<uchar>(i,j)=sto.at<uchar>(i-1,j);
                   else if(sto.at<uchar>(i-1,j-1)!=0)
                     sto.at<uchar>(i,j)=sto.at<uchar>(i-1,j-1);
                   else if(sto.at<uchar>(i-1,j+1)!=0)
                     sto.at<uchar>(i,j)=sto.at<uchar>(i-1,j+1);
                   else if(sto.at<uchar>(i,j-1)!=0)
                     sto.at<uchar>(i,j)=sto.at<uchar>(i,j-1);
                 }
                 else
                 {
                    if(sto.at<uchar>(i-1,j)!=0)
                      sto.at<uchar>(i,j)=sto.at<uchar>(i-1,j);
                 }
            }
        }
    }

    cout<<"here2\n";

//remove
int temp;
    for (int i=1;i<img.rows-1;i++)
    {
        cout<"memory\n";
        for (int j=1;j<img.cols-1;j++)
        {   
            //cout<"memory\n";
            temp=sto.at<uchar>(i,j);
            ct[temp]++;
        }
    }

    for (int i=1;i<img.rows-1;i++)
    {
        for (int j=1;j<img.cols-1;j++)
        {
            if (ct[sto.at<uchar>(i,j)]>15)
              sto.at<uchar>(i,j)=255;
            else
              sto.at<uchar>(i,j)=0;
        }
    }




return sto;

}

`

When I run this code It runs till the "here2" cout and after that it gives the above mentioned error. I have no idea why that's happening.

edit retag flag offensive close merge delete

Comments

You're accessing sto.at(i-1, j+1) but j+1 is an invalid index at the end of the loop. Try changing that.

Tetragramm gravatar imageTetragramm ( 2016-05-14 18:34:48 -0600 )edit
1

you're reinventing connectedComponents -- worse ;(

berak gravatar imageberak ( 2016-05-14 21:47:08 -0600 )edit

vector<int> ct(1,wd*ht); you're accessing ct with uchar [0..255] elements, so your dimensions here are for sure wrong.

berak gravatar imageberak ( 2016-05-15 03:25:28 -0600 )edit