简体   繁体   English

OpenCV C++ 内存泄漏问题

[英]OpenCV C++ memory leak issue

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.运行后的问题是 - ram 不断填充。 I have 48 gb of ram, which got filled in just some minutes as the loop runs.我有 48 GB 的内存,在循环运行的几分钟内就被填满了。

If i am releasing the memory, then why it keeps acquiring my ram.如果我要释放内存,那么为什么它会不断获取我的内存。

A cv::Mat object contains metadata (width, height etc.) and a pointer to the image data.cv::Mat对象包含元数据(宽度、高度等)和指向图像数据的指针。

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).正如您在链接中看到的那样, cv::Mat::release方法释放了为cv::Mat数据分配的内存(假设 ref-count 为 0)。
It does not free the memory for the cv::Mat object itself (ie the instance of the class containing the medadata and data pointer).它不会为cv::Mat对象本身(即包含 medadata 和数据指针的类的实例)释放内存。

In your case the object is allocated on the heap using new and therfore should be freed with a corresponding delete .在您的情况下,该对象是使用new在堆上分配的,因此应该使用相应的delete释放。

However - it is not clear why you use new at all.但是-根本不清楚为什么要使用new You can have the cv::Mat on the stack as an automatic variable:您可以将堆栈上的cv::Mat作为自动变量:

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.请注意,如果您需要手动释放cv::Mat对象指向的数据,您仍然可以使用release In your case above it is not needed because the destrcutor of cv::Mat will take care of it for you.在您上面的情况下,它是不需要的,因为cv::Mat的 destrcutor 会为您处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM