title: c++ memory leak using threads
body: <p>I have a memory leak with this piece of code and I don't understand why.</p>
  
  <p>Each thread calls the function exec. The function exec simply creates a std::vector and than delete it. This vector has length equal to the number of threads and it is created, and deleted, only once. </p>
  
  <p>You can suppose that this code is thread-safe in the sense that the vector is deleted only after the creation.  </p>
  
  <pre><code>class Foo{
    public:
    Foo(const std::size_t&amp; numThreads):size_(numThreads){}
    inline void alloc(){std::call_once(bufferflag_,&amp;Foo::alloc_,this);}
    inline void free(){std::call_once(bufferflag_,&amp;Foo::free_,this);}
  
    private:
    const std::size_t size_;
    std::vector&lt;double&gt;* bufferptr_;
    std::once_flag bufferflag_;
  
    inline void alloc_(){bufferptr_ = new std::vector&lt;double&gt;(size_);}
    inline void free_(){delete [] bufferptr_;}
  };
  
  void exec(Foo&amp; comm){
    comm.alloc();
    // sync the threads here with some barrier
    comm.free();
  }
  
  void main(){
    Foo comm(10);
    std::vector&lt;std::thread&gt; t(10);
    for(std::size_t tid=0;tid!=10;++tid) t[tid]=std::thread(exec,std::ref(comm));
    for(std::size_t tid=0;tid!=10;++tid) t[tid].join();
  }
  </code></pre>
  
  <p>HEAP SUMMARY:</p>
  
  <p>in use at exit: 104 bytes in 2 blocks</p>
  
  <p>total heap usage: 23 allocs, 21 frees, 3,704 bytes allocated</p>
  
  <p>104 (24 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2</p>
  
  <p>LEAK SUMMARY:</p>
  
  <p>definitely lost: 24 bytes in 1 blocks</p>
  
  <p>indirectly lost: 80 bytes in 1 blocks</p>
  
  <p>possibly lost: 0 bytes in 0 blocks</p>
  
  <p>still reachable: 0 bytes in 0 blocks</p>
  
  <p>suppressed: 0 bytes in 0 blocks</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>If instead of using call_once I just call the new and delete from the same thread, there are no memory leaks.</p>