Home > Enterprise >  OpenCV C memory leak issue
OpenCV C memory leak issue

Time:05-26

Just see the below code snippet -

# include "opencv4/opencv2/opencv.hpp"
# include "iostream"
int main() {
    while (true) {
        cv::Mat* mat = new cv::Mat(2000, 2000, CV_8UC3);
        std::cout << "mat size" << mat->size() << std::endl;
        mat->release();
        std::cout << "mat size after" << mat->size() << std::endl;
    }
}

Problem after running is - ram keep filling. I have 48 gb of ram, which got filled in just some minutes as the loop runs.

If i am releasing the memory, then why it keeps acquiring my ram.

CodePudding user response:

A cv::Mat object contains metadata (width, height etc.) and a pointer to the image data.

As you can see in the link, the cv::Mat::release method frees the memory allocated for the cv::Mat data (assuming the ref-count is 0).
It does not free the memory for the cv::Mat object itself (i.e. the instance of the class containing the medadata and data pointer).

In your case the object is allocated on the heap using new and therfore should be freed with a corresponding delete.

However - it is not clear why you use new at all. You can have the cv::Mat on the stack as an automatic variable:

cv::Mat mat(2000, 2000, CV_8UC3);

This way it's destructor (and deallocation) will be called automatically at the end of the scope.

Note that you can still use release if you need to free the data pointed by the cv::Mat object manually. In your case above it is not needed because the destrcutor of cv::Mat will take care of it for you.

  • Related