my program is failing with stack smashing detected and the only messages than I have from Valgring is “blocks are possibly lost in loss record” repetead three times, and
I don’t know how to solved.
==3726== 144 bytes in 1 blocks are possibly lost in loss record 74 of 87
==3726== at 0x4025315: calloc (vg_replace_malloc.c:467)
==3726== by 0x4010CD7: allocate_dtv (dl-tls.c:300)
==3726== by 0x401146B: _dl_allocate_tls (dl-tls.c:464)
==3726== by 0x40405C6: pthread_create@@GLIBC_2.1 (allocatestack.c:570)
==3726== by 0x806BF36: Thread::Thread(void* (*)(void*), void*) (os.cpp:203)
this is the code and Valgrind is pthread_create call.
Thread::Thread( PFUNC func, void * arg )
{
int s = pthread_create( &_ThreadId, NULL, func, arg); //here is msg from valgrind
if (s != 0)
throw EXCEPT_NOTHREAD;
pthread_detach( _ThreadId );
}
Please can you help me what is wrong with the Thread function? I read in other similar questions that pthread_detach has to be before to create a thread?
thanks a lot in advance.
There’s nothing “wrong” as such; it’s just not releasing the thread’s resources before the end of the program, and Valgrind is reporting this as a memory leak. Since you’ve detached the thread, its resources won’t be released until the thread terminates. If it doesn’t terminate before the program does, then they might be reported as leaked.
You don’t need to use
pthread_detach; that’s used to make the thread responsible for freeing its own resources. If you don’t use it, then another thread will need to callpthread_joinwhen it’s time to stop the thread.If you want to clean up the leak, then instead of detaching the thread, you’ll have to keep hold of the thread handle (which I guess you’re already doing, assuming
_ThreadIdis a member variable). Then, before the program ends, tell the thread to stop and then callpthread_jointo wait for it and release all of its resources. Whether it’s worth the hassle of doing that to remove a (probably harmless) warning is up to you, but a clean shutdown might help to avoid more serious potential problems.By the way, you shouldn’t use names like
_ThreadIdwhich start with a_followed by an upper-case letter; names like that are reserved.