I have a program that runs some action in a separate therad, then joins on the thread, such as this one:
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void f() {
for (int i = 0; i < 100; ++i) cout << i << endl;
}
int main() {
boost::thread t(f);
t.join();
return 0;
}
If I run Valgrind on it, it reports 'possibly lost' memory. This seems logical if I omit the join()
, because in that case the thread is still running when the program exits. But if the thread is finished, I would expect that there are no warnings.
Here is the backtrace:
==8797== 288 bytes in 1 blocks are possibly lost in loss record 2 of 3
==8797== at 0x4A1F8B3: calloc (vg_replace_malloc.c:467)
==8797== by 0x400F289: allocate_dtv (in /lib64/ld-2.4.so)
==8797== by 0x400F34D: _dl_allocate_tls (in /lib64/ld-2.4.so)
==8797== by 0x53EF981: pthread_create@@GLIBC_2.2.5 (in /lib64/libpthread-2.4.so)
==8797== by 0x4B3311D: boost::thread::start_thread() (in /home/egbomrt/BOOST/inst_1_47_0/lib/libboost_thread.so.1.47.0)
==8797== by 0x40A20C: boost::thread::thread<void (*)()>(void (*)(), boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (*)()> >, boost::thread::dummy*>::type) (thread.hpp:204)
==8797== by 0x406295: main (main.cpp:12)
Is this a problem with Boost Thread, Posix Thread or is this perfectly normal? I could just create a suppression rule for it, but it would also be good if I got a warning if there is an unfinished thread, but not when all threads are finished.
possibly lost: heap-allocated memory that was never freed to which valgrind cannot be sure whether there is a pointer or not. still reachable: heap-allocated memory that was never freed to which the program still has a pointer at exit (typically this means a global variable points to it).
If you compile your program with the -g flag, Valgrind will show you the function names and line numbers where errors occur. Sometimes the actual bug occurs on a different line (particularly for uninitialized value errors) but the line number Valgrind tells you is a good starting point.
If you give the -v option, Valgrind will print the list of used suppressions at the end of execution. For a leak suppression, this output gives the number of different loss records that match the suppression, and the number of bytes and blocks suppressed by the suppression.
I found that the problem is with the pthread library. If I run the program on SUSE 10, I get the memory leaks, but if I run it on SUSE 11, I don't get the problem.
I get the same results with and without Boost.
Thanks for the comments. That helped me pinpoint the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With