Search code examples
c++segmentation-faultmalloc

segmentation fault: Malloc problem when i try to create a cv::mat


I am trying to create a cv::Mat to process image pyramid, the source code is from ORBSLAM3 and I added something new, Im getting this output and here is my code:(the error appears not everytime running through this part of code)

void ORBextractor::ComputePyramid(cv::Mat image, cv::Mat Mask) {
        for (int level = 0; level < nlevels; ++level)
        {
            // cout << "error-0" << endl;
            float scale = mvInvScaleFactor[level];
            Size sz(cvRound((float)image.cols*scale), cvRound((float)image.rows*scale));
            Size wholeSize(sz.width + EDGE_THRESHOLD*2, sz.height + EDGE_THRESHOLD*2);
            cout << "error-0-1" << endl;
            cout << "error-1" << endl;
            cv::Mat temp(wholeSize, image.type()); // program crushed here
            mvImagePyramid[level] = temp(Rect(EDGE_THRESHOLD, EDGE_THRESHOLD, sz.width, sz.height));

            if (!Mask.empty()) {
                // masktemp = Mat(wholeSize, Mask.type());
                // mvMaskPyramid[level] = masktemp(Rect(EDGE_THRESHOLD, EDGE_THRESHOLD, sz.width, sz.height));
                cv::Mat resized_mask(sz, Mask.type());
                // cout << "error-2" << endl;
                resize(Mask, resized_mask, sz, 0, 0, INTER_NEAREST);
                resized_mask.copyTo(mvMaskPyramid[level]);
            }

            // Compute the resized image
            if( level != 0 )
            {
                resize(mvImagePyramid[level-1], mvImagePyramid[level], sz, 0, 0, INTER_LINEAR);

                copyMakeBorder(mvImagePyramid[level], temp, EDGE_THRESHOLD, EDGE_THRESHOLD, EDGE_THRESHOLD, EDGE_THRESHOLD,
                               BORDER_REFLECT_101+BORDER_ISOLATED);
            }
            else
            {
                copyMakeBorder(image, temp, EDGE_THRESHOLD, EDGE_THRESHOLD, EDGE_THRESHOLD, EDGE_THRESHOLD,
                               BORDER_REFLECT_101);
            }

        }
    }

enter image description here

Im quite new in opencv, can anyone tell me why I get this error.


Solution

  • When opencv library was compiled in release version, some of its assertion wont work, such as mat.at(i,j), you illigally access the memory out of the range, opencv's CV_DbgAssert wont warn you, and then you try to allocate memory and sometimes it happens to allocate the memory which was illigally modified, and caused this error. And thanks for all helps.