[英]Memory leak with opencv imwrite
I am trying to write the frames that come in from a stream to an external hard disk conencted via USB in.jpg format.我正在尝试将来自 stream 的帧写入通过 USB in.jpg 格式连接的外部硬盘。 But I observe a memory leak when I run this C++ program.
但是当我运行这个 C++ 程序时,我观察到 memory 泄漏。 The interesting point is that when I overwrite the same image file(same name and path) I don't see a memory leak, but I write new file(new name and path) for every incoming frame, my computer's RAM gets filled up.
有趣的一点是,当我覆盖相同的图像文件(相同的名称和路径)时,我没有看到 memory 泄漏,但是我为每个传入的帧写入新文件(新名称和路径),我的计算机的 RAM 被填满。 I am using a single cv::Mat initialised at the start of the program and storing each incoming frame in that Mat.
我正在使用在程序开始时初始化的单个 cv::Mat 并将每个传入帧存储在该 Mat 中。 And then I write this Mat to the disk using cv::imwrite.
然后我使用 cv::imwrite 将此 Mat 写入磁盘。 I don't know why this is happening.
我不知道为什么会这样。 Can you guys suggest something?
你们能推荐点什么吗?
Here is the code:这是代码:
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
VideoCapture cap("testVid.mp4");
if(!cap.isOpened()){
cout << "Error opening video stream or file" << endl;
return -1;
}
Mat *writeMat = new Mat();
int frame_num = 0;
while(1){
cap >> *writeMat;
if (writeMat->empty())
break;
char *imageName = (char*)malloc(64*sizeof(char));
//Storage mounted at /mnt/disk1
sprintf(imageName, "/mnt/disk1/%07d.jpg", frame_num);
imwrite(imageName, *writeMat);
free(imageName);
}
cap.release();
delete writeMat;
writeMat = NULL;
return 0;
}
Most probably the memory leak is due to the fact you alloacted an array ( char *imageName = new char[64]
) but you did not delete it using the array specific delete call: delete [] imageName;
memory 泄漏很可能是由于您分配了一个数组(
char *imageName = new char[64]
),但您没有使用数组特定的删除调用删除它: delete [] imageName;
You do not need to allocated dynamically here.您不需要在这里动态分配。 Since you are using a local variable of a loop you can simply do:
由于您使用的是循环的局部变量,因此您可以简单地执行以下操作:
{
// ...
char imageName[64];
// imageName will be cleaned up when unscoped from the current loop
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.