Deepak
Deepak

Reputation: 1088

How to prevent memory leak in code

I have called cvCreateStructuringElementEx() function (which returns IplConvKernel*) inside cvDilate function.

How can I prevent a memory leak if I have called cvDilate as given below ?

#include <iostream>
#include <cv.h>
#include <highgui.h>
using namespace std;

int main()
{
  IplImage* topHatImg = cvLoadImage("ff.jpg",0);
  for (size_t i = 0; i < 1000000; i++)
  {
    //memory leak due to repeated call to cvCreateStructuringElementEx()
    //how can I prevent this
    cvDilate(topHatImg, topHatImg,
             cvCreateStructuringElementEx(21, 3, 11, 2, CV_SHAPE_RECT,NULL ));
  }
}

Upvotes: 2

Views: 373

Answers (2)

karlphillip
karlphillip

Reputation: 93410

@KeillRandoris gave the right answer. I apologize for adding another extremely similar answer but I wanted to talk a little bit more about the issue and share some code for better visualization.

As you identified in the question, the leak happens because cvCreateStructuringElementEx() allocates dynamic memory when called, which means that if you don't invoke cvReleaseStructuringElement() at every iteration to release that memory, the leak is going to happen:

IplImage* topHatImg = cvLoadImage("ff.jpg",0);
for (size_t i = 0; i < 1000000; i++)
{      
    IplConvKernel* element= cvCreateStructuringElementEx(21, 3, 11, 2, CV_SHAPE_RECT,NULL);
    cvDilate(topHatImg, topHatImg, element);
    cvReleaseStructuringElement(&element);
}

cvReleaseImage(&topHatImg);

Upvotes: 2

Яois
Яois

Reputation: 3858

Either do as suggested in the comments or create the IplConvKernel structure out of the loop:

IplImage* topHatImg = cvLoadImage("ff.jpg",0);
IplConvKernel* convKernel = cvCreateStructuringElementEx(21, 3, 11, 2, CV_SHAPE_RECT,NULL );
for (size_t i = 0; i < 1000000; i++)
{      
  cvDilate(topHatImg, topHatImg,convKernel);
}
// deallocate stuff here
cvReleaseStructuringElement(&convKernel);
cvReleaseImage(&topHatImg);
// ...

I'll recommend you to switch to OpenCV C++ API.

Upvotes: 3

Related Questions