Releasing OpenCV IplImage crashes the application?
I have an problem freeing up memory allocated for an IplImage.I have given a similar situation as in my application below.(it reflects the same bug occurs in my application.)
But instead of the line
char* originalData=loadedImage->imageData;
I get my "originalData" from a QT QImage class. Code crashes at the line where 开发者_如何学JAVAI free "image_gray".
cvReleaseImage(&img_gray); // <-- crashes
Error message -
OpenCV Error: Assertion failed (udata < (uchar*)ptr && ((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+16)) in fastFree, file C:\opt\OpenCV-2.2.0\modules\co e\src\alloc.cpp, line 76 terminate called after throwing an instance of 'cv::Exception' what(): C:\opt\OpenCV-2.2.0\modules\core\src\alloc.cpp:76: error: (-215) uda a < (uchar*)ptr && ((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+16) in fu ction fastFree
But if I use cvReleaseImageHeader() instead, if works fine but leaving a memory leak.
Any suggestions please?
void test2( char *imageFileName)
{
IplImage *loadedImage=cvLoadImage(imageFileName);
int xsize=loadedImage->width;
int ysize=loadedImage->height;
int totalBytes=xsize*ysize;
//In my application this "originalData" data comes from a QT QImage.
char* originalData=loadedImage->imageData;
unsigned char* datacopy = new unsigned char [totalBytes];
memcpy(datacopy, originalData, totalBytes);
IplImage* img_gray = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_gray_copy = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_edge = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_mask = cvCreateImage(cvSize(xsize, ysize), IPL_DEPTH_8U, 1);
cvSet(img_mask, cvScalar(255));
cvSet(img_gray_copy, cvScalar(255));
cvSetZero(img_mask);
cvSetData(img_gray, datacopy, xsize);
cvCopy(img_gray, img_gray_copy, img_mask);
//cvThreshold(img_gray_copy, img_edge, threshold, 255, CV_THRESH_BINARY_INV);
//cvFindContours(img_edge, storage, contours, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
cvReleaseImage(&img_gray); /// <--- this crashes the application
//cvReleaseImageHeader(&img_gray); //<--- this works.but leaving a memory leak ???
cvReleaseImage(&img_gray_copy);
cvReleaseImage(&img_edge);
cvReleaseImage(&img_mask);
}
Ok found the issue. I should have used cvCreateImageHeader() for img_gray .And then manually delete allocated memory.
精彩评论