1
votes

I am trying to write the frames that come in from a stream to an external hard disk conencted via USB in .jpg format. But I observe a memory leak when I run this C++ program. 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. I am using a single cv::Mat initialised at the start of the program and storing each incoming frame in that Mat. And then I write this Mat to the disk using cv::imwrite. 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;
}
1
Without a minimal reproducible example it is not possible to tell why this is the case.t.niese

1 Answers

1
votes

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;

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
}