qtmemory-leaksparallel-processingqfuture

QFuture Memoryleak


I want to parallelize a function and have the problem that after a few hours my memory is overloaded.

The test program calculates something simple, and works so far. Only the memory usage is constantly increasing.

QT Project file:

QT -= gui
QT += concurrent widgets
CONFIG += c++11 console
CONFIG -= app_bundle
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp

QT program file:

#include <QCoreApplication>
#include <qdebug.h>
#include <qtconcurrentrun.h>

double parallel_function(int instance){
    return (double)(instance)*10.0;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int nr_of_threads = 8;
    double result_sum,temp_var;
    for(qint32 i = 0; i<100000000; i++){
      QFuture<double> * future = new QFuture<double>[nr_of_threads];

      for(int thread = 0; thread < nr_of_threads; thread++){
        future[thread] = QtConcurrent::run(parallel_function,thread);
      }
      for(int thread = 0; thread < nr_of_threads; thread++){
        future[thread].waitForFinished();
        temp_var = future[thread].result();
        qDebug()<<"result: " << temp_var;
        result_sum += temp_var;
      }
  }

  qDebug()<<"total: "<<result_sum;
  return a.exec();
}

As I have observed, QtConcurrent::run(parallel_function,thread) allocates memory, but does not release memory after future[thread].waitForFinished().

What's wrong here?


Solution

  • You have memory leak because future array is not deleted. Add delete[] future at the end of outer for loop.

    for(qint32 i = 0; i<100000000; i++)
    {
       QFuture<double> * future = new QFuture<double>[nr_of_threads];
    
       for(int thread = 0; thread < nr_of_threads; thread++){
         future[thread] = QtConcurrent::run(parallel_function,thread);
       }
       for(int thread = 0; thread < nr_of_threads; thread++){
          future[thread].waitForFinished();
          temp_var = future[thread].result();
          qDebug()<<"result: " << temp_var;
          result_sum += temp_var;
       }
    
       delete[] future; // <--
    }