2017-06-20 5 views
0

valgrindの下で実行すると、まだいくつかのブロックに到達可能であると表示されます。コードには明示的なリークはありませんが。 なぜこれが起こっているのですか?stdスレッドのベクトルのvalgrind出力にまだ到達可能なブロック

助けてください?

valgrindのトレースは、コードは以下である

==5059== 32 bytes in 1 blocks are still reachable in loss record 1 of 1 
==5059== at 0x4C2C20C: operator new(unsigned long) (vg_replace_malloc.c:334) 
==5059== by 0x402A67: __gnu_cxx::new_allocator<std::thread>::allocate(unsigned long, void const*) (new_allocator.h:104) 
==5059== by 0x402986: std::allocator_traits<std::allocator<std::thread> >::allocate(std::allocator<std::thread>&, unsigned long) (alloc_traits.h:416) 
==5059== by 0x40280F: std::_Vector_base<std::thread, std::allocator<std::thread> >::_M_allocate(unsigned long) (stl_vector.h:170) 
==5059== by 0x402493: void std::vector<std::thread, std::allocator<std::thread> >::_M_emplace_back_aux<std::thread>(std::thread&&) (vector.tcc:412) 
==5059== by 0x402008: void std::vector<std::thread, std::allocator<std::thread> >::emplace_back<std::thread>(std::thread&&) (vector.tcc:101) 
==5059== by 0x40188F: std::vector<std::thread, std::allocator<std::thread> >::push_back(std::thread&&) (stl_vector.h:933) 
==5059== by 0x4012D0: main (t3.cpp:25) 

==5059== LEAK SUMMARY: 
==5059== definitely lost: 0 bytes in 0 blocks 
==5059== indirectly lost: 0 bytes in 0 blocks 
==5059==  possibly lost: 0 bytes in 0 blocks 
==5059== still reachable: 32 bytes in 1 blocks 
==5059==   suppressed: 0 bytes in 0 blocks 
==5059== 

あります。 exit(0)をごmain()からではなくreturn 0で呼び出されるためである

#include<iostream> 
#include<vector> 
#include<string> 
#include<mutex> 
#include<thread> 

using namespace std; 

std::mutex g_mutex; 

void dosomework(const int& id) 
{ 
    std::lock_guard<std::mutex> lock(g_mutex); 
    cout << "I am doing some work in thread id = " << id << endl; 
} 


int main(int argc, char* argv[]) 
{ 

    std::vector<std::thread> threads; 
    threads.reserve(3); 

    for(unsigned int i=0; i<3; ++i) 
     threads.push_back(std::thread(dosomework,i)); 

    std::this_thread::sleep_for(std::chrono::seconds(10)); 

    for(auto& t : threads) 
    { 

     if(t.joinable()) 
     { 
      cout << "joining the thread" << endl; 
      t.join(); 
     } 
     else 
     { 
      cout << "thread is not joinable" << endl; 
     } 
    } 

    exit(0); 
} 

答えて

2

returnmain()で呼び出された場合、デストラクタはローカルスコープのオブジェクトに対して呼び出されますが、exit()が呼び出されると、そうではありません。

+0

はい基本の基礎私はそれを逃した。出口を使うのは悪い考えで、ほとんど常にそれを避けるべきです。 –

関連する問題