Occasional false positive memory leak when using std::future and _CrtMemDifference on Windows

210 views Asked by At

Below is a minimal repro of the memory leak I see when using std::future. Inside ParallelForEach I create an array of std::future with a subsequent get that should block the execution of the main thread until all the tasks for vec are finished. Once the function ParallelForEach returns, the vector of futures must be cleaned up. But building with debug and _CrtMemDifference I see an occasional memory leak which I suspect to be false positive and its just windows not cleaning up the threads in time until process exit.

Total bytes leaked: 49128

This is a problem since I have mem leak check in my tests that I don't want to get rid of. Why does this leak happen and how can I use both _CrtMemDifference and std::future?

#include <iostream>
#include <vector>
#include <future>
#include <crtdbg.h>

int func(int x) {
  return x * x;
}

void ParallelForEach(const std::vector<int>& vec) {
  std::vector<std::future<int>> futures;
  for (const auto& x : vec) {
    futures.push_back(std::async(std::launch::async, func, x));
  }
  for (auto& f : futures) {
    f.get();
  }
}

void MemoryLeakTest()
{
  std::vector<int> vec(64, 12);

  _CrtMemState before;
  _CrtMemCheckpoint(&before);

  ParallelForEach(vec);

  _CrtMemState after;
  _CrtMemCheckpoint(&after);

  _CrtMemState leaked;
  if (_CrtMemDifference(&leaked, &before, &after) != 0) {
    std::cout << "Total bytes leaked: " << leaked.lTotalCount << std::endl;
  }
}

int main() {
  for (int i = 0; i < 10000; i++)
  {
    MemoryLeakTest();
  }
  return 0;
}

I tried std::for_each with parallel execution and this works without mem leak, but is not available in all targeted systems. I expect there to be a way/workaround to use std::future without Crt reporting false memory leaks.

0

There are 0 answers