C++ – Do I need a cvReleaseImage if image is returned

c++memory-managementopencv

I'm working with OpenCV 2.2 and I'm wondering if I have to release the memory I allocated for an image if the image is returned. I have method1 (see below) that is called from the main program several times. It returns an IplImage that was created inside the method.
Where do I have to release the image created in the method? If I release it before the return command nothing will be returned I guess? After the return command, it will not be processed. So how do I get rid of all the dst Images created during runtime of my program???

IplImage* Method1(IplImage* src) {
 IplImage *dst = cvCreateImage(cvSize(src->width, src->height), IPL_DEPTH_8U, 1);
 [...]
 return dst;
}

Thx!

EDIT:
So should I call this method like this:

IplImage* tmp;
tmp = cvCreateImage(cvSize(dst->width, dst->height), IPL_DEPTH_8U, 1);
tmp = Method1(src);

or

IplImage* tmp;
tmp = Method1(src);

to release the memory correctly in the main program afterwards?

Best Solution

  1. If you're using C++, don't use IplImage*, use cv::Mat, which does memory management automatically for you.
  2. Your first method creates a memory leak (this is not opencv-specific - you allocate the memory for something, then overwrite the pointer so it's now inaccessible (this means you have an allocation that does nothing, and you will never be able to free that.
Related Question