samedi 27 avril 2013

Memory Managment in OpenCV_C++

Unlike Java language, C++ isn't a garbage collector, therefore you need to manually deallocates memory every time its use is over. If you ignore this detail, you will have out-of-memory problem since your RAM couldn't supply all the space you are asking for. So you need to know perfectly handling the memory space you are using.
In the following sections I will show briefly how to get rid of allocated memory.

new and delete
if you allocate memory using new, you compulsorily deallocate memory using delete operator:
- Memory allocation/deallocation for an integer
// allocate memory using new operator 
int *var = new int
//deallocates memory using delete operator 
delete var;
- Memory allocation/deallocation for a table
//Allocate table of 100 elements
int *a = new int[100];
//Delete the array element
delete [] a; a = NULL;

create and release
To fix the memory leak problems with OpenCV, you should check if you have release the object you have already created. In OpenCV there are many create function and their corresponding release function. If you are creating something and want later to return it, make sure that you didn't release it. 
Here some list of the most used functions:
CvSeq -- > cvClearSeq
CvMemStorage --> cvReleaseMemStorage
CvHaarClassifierCascade --> cvReleaseHaarClassifierCascade
cvCreateImageHeader –-> cvReleaseImageHeader
cvCreateImage –-> cvReleaseImage
cvCreateMat –-> cvReleaseMat
cvCreateMatND –-> cvReleaseMatND
cvCreateData –-> cvReleaseData
cvCreateSparseMat –-> cvReleaseSparseMat
cvCreateGraphScanner –-> cvReleaseGraphScanner
- cvOpenFileStorage –-> cvReleaseFileStorage
cvAlloc –-> cvFree
- ... etc.

If you have create a table of image, before releasing the table (with delete) you need to go over each table case and release the allocated image (of course after its use is over). Here is an example:
// Allocation of table of images
IplImage** TabImg = new IplImage* [NbImage];
for(int i=0; i<NbImage; i++)
{TabImg[i]=cvCreateImage(cvSize(100, 100), IPL_DEPTH_8U, 1); }
// Use the Table of image 
//Free the Table of images
for(int i=0; i<NbImage; i++)
 {cvReleaseImage(&TabImg[i]);} //Free each table case
 delete[] TabImg; TabImg = NULL; //Free the tale itself

Then your memory is pretty free ...

Freedom is good not only for human but also for memory ;-)

Aucun commentaire:

Enregistrer un commentaire