Memory leak in a simple example c++ program of std::execution::par

469 Views Asked by At

I was learning about parallel execution in c++ as I stumbled across this simple example:

test.cpp:

#include <algorithm>
#include <execution>
#include "./profile.h"
#include <vector>

int main() {
    std::vector<int> testSeq(10000000, std::rand());
    std::vector<int> testPar(10000000);
    std::copy(testSeq.begin(), testSeq.end(), testPar.begin());
    {
        LOG_DURATION("seq");
        std::sort(testSeq.begin(), testSeq.end());
    }
    {
        LOG_DURATION("par");
        std::sort(std::execution::par, testPar.begin(), testPar.end());
    }
}

profile.h:

#pragma once

#include <chrono>
#include <iostream>
#include <optional>
#include <sstream>
#include <string>

class LogDuration {
 public:
  explicit LogDuration(const std::string& msg = "")
    : message(msg + ": ")
    , start(std::chrono::steady_clock::now()) {
  }

  ~LogDuration() {
    auto finish = std::chrono::steady_clock::now();
    auto dur = finish - start;
    std::ostringstream os;
    os << message
       << std::chrono::duration_cast<std::chrono::milliseconds>(dur).count()
       << " ms" << std::endl;
    std::cerr << os.str();
  }
 private:
  std::string message;
  std::chrono::steady_clock::time_point start;
};

#ifndef UNIQ_ID
  #define UNIQ_ID_IMPL(lineno) _a_local_var_##lineno
  #define UNIQ_ID(lineno) UNIQ_ID_IMPL(lineno)
#endif

#define LOG_DURATION(message) \
  LogDuration UNIQ_ID(__LINE__){message};

It should demonstrate performance improvements of parallel execution, however according to sanitizer it has a memory leak somewhere in there:

g++ --std=c++17 test.cpp -fsanitize=address -ltbb && ./a.out
seq: 6821 ms
par: 1757 ms

=================================================================
==2585017==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1560 byte(s) in 3 object(s) allocated from:
    #0 0x7ff008e920c1 in operator new[](unsigned long) /build/gcc/src/gcc/libsanitizer/asan/asan_new_delete.cpp:102
    #1 0x7ff008dbe33e  (/usr/lib/libtbb.so.2+0x2633e)

SUMMARY: AddressSanitizer: 1560 byte(s) leaked in 3 allocation(s).

Am I using this wrong or something?

0

There are 0 best solutions below