Could somebody explain me why this peace of code produces memory leak(s)?
Boost 1.49 and boost-1.53 gives the same result....
#include <boost/thread.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
boost::mutex mutex;
boost::condition_variable_any cond;
std::vector<int> random_numbers;
void fill()
{
std::srand(static_cast<unsigned int>(std::time(0)));
for (int i = 0; i < 3; ++i)
{
boost::unique_lock<boost::mutex> lock(mutex);
random_numbers.push_back(std::rand());
cond.notify_all();
cond.wait(mutex);
}
}
void print()
{
std::size_t next_size = 1;
for (int i = 0; i < 3; ++i)
{
boost::unique_lock<boost::mutex> lock(mutex);
while (random_numbers.size() != next_size)
cond.wait(mutex);
std::cout << random_numbers.back() << std::endl;
++next_size;
cond.notify_all();
}
}
int main()
{
boost::thread t1(fill);
boost::thread t2(print);
t1.join();
t2.join();
}
Here is valgrind output:
valgrind --leak-check=full --show-reachable=yes ./a.out
==3079== Memcheck, a memory error detector
==3079== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==3079== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==3079== Command: ./a.out
==3079==
val: 535293148
val: 1979778795
val: 1888522902
==3079==
==3079== HEAP SUMMARY:
==3079== in use at exit: 8 bytes in 1 blocks
==3079== total heap usage: 16 allocs, 15 frees, 1,732 bytes allocated
==3079==
==3079== 8 bytes in 1 blocks are still reachable in loss record 1 of 1
==3079== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3079== by 0x4E45BF9: boost::detail::get_once_per_thread_epoch() (in /usr/local/lib/libboost_thread.so.1.53.0)
==3079== by 0x4E3F861: _ZN5boost9call_onceIPFvvEEEvRNS_9once_flagET_.constprop.239 (in /usr/local/lib/libboost_thread.so.1.53.0)
==3079== by 0x4E3F978: boost::detail::get_current_thread_data() (in /usr/local/lib/libboost_thread.so.1.53.0)
==3079== by 0x40A909: boost::detail::interruption_checker::interruption_checker(pthread_mutex_t*, pthread_cond_t*) (in /u00/system/workspace/shared_lock2/src/a.out)
==3079== by 0x4E40502: boost::thread::join_noexcept() (in /usr/local/lib/libboost_thread.so.1.53.0)
==3079== by 0x40ACAE: boost::thread::join() (in /u00/system/workspace/shared_lock2/src/a.out)
==3079== by 0x4092B0: main (in /u00/system/workspace/shared_lock2/src/a.out)
==3079==
==3079== LEAK SUMMARY:
==3079== definitely lost: 0 bytes in 0 blocks
==3079== indirectly lost: 0 bytes in 0 blocks
==3079== possibly lost: 0 bytes in 0 blocks
==3079== still reachable: 8 bytes in 1 blocks
==3079== suppressed: 0 bytes in 0 blocks
==3079==
==3079== For counts of detected and suppressed errors, rerun with: -v
==3079== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
This source is part of cpp book from http://en.highscore.de/cpp/boost/