Friday, January 2, 2015

Avoiding Memory Crash

To debug memory leaks which leads to crashes. I use Xcode's Instrument called Leaks. You can access this tool from Xcode/Open Developer Tool/Instruments in the menu bar. Alternatively, click Product/Profile. You will need to select the app to profile. Below is the screen shot of the Leaks tool. The app crashed after about 2 mins running an iOS OpenCV app. The Persistent memory started at about 20MB and climbed steadily until at 671 MB,  and crashed. The Xcode console also shows a few didReceiveMemoryWarning events. Malloc is the culprit utilizing 657MB as can be seen from the screenshot.

The below shows memory efficient app after fixing the code that caused memory leaks. It was still running after 2 minutes, with Persistent memory at only 13.6 MB. The memory stayed stable at between 8 - 15MB throughout the 2 minutes, indicating zero memory leaks.

To fix memory leaks. Here are the tips.

Use C++, instead of C:

Mat intead of IplImage, 
Point instead of CvPoint, 
cv::function() instead of cvFunction. 
CvSeq is replaced by std::vector<T>
And do not declare pointers to images if possible:
Mat src = imread("myfile.jpg");
Mat gray; // note that I do not allocate it. 
// This is done automatically in the next functions
cv::cvtColor(src, gray, CV_BGR2GRAY);

No comments:

Post a Comment