Ask Your Question

Revision history [back]

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

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.