The simple test:
void testMemoryLeak_PthreadCreateJoin(void)
{
auto taskFunction = [](void*args) -> void*
{
return nullptr;
};
pthread_t pth;
int err = pthread_create(&pth, /*attr*/nullptr, taskFunction, /*args*/nullptr);
pthread_join(pth, nullptr);
}
void main(void)
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
testMemoryLeak_PthreadCreateJoin();
testMemoryLeak_PthreadCreateJoin();
testMemoryLeak_PthreadCreateJoin();
testMemoryLeak_PthreadCreateJoin();
}
Here said:
A thread is an allocated resource and you did not free it before exiting. You should call
pthread_join
; this would also eliminate the need for your hackish and incorrect sleep loop.It's possible that even once you fix this, valgrind will still see a "leak", since some implementations of POSIX threads (I'm guessing you're using glibc/NPTL) cache and reuse thread resources rather than freeing them fully. I'm not sure if valgrind works around this or not.
But I already use pthread_join
. I use VS2015 and its heap analyzer. Could the problem be in pthread
my particular implementation? I use PAL by Dongsheng Song
Causes memory leakage:
Detected memory leaks!
Dumping objects ->
{104} normal block at 0x007742C0, 24 bytes long.
Data: < X > D8 00 00 00 E0 58 20 00 00 00 00 00 00 00 00 00
{101} normal block at 0x00774398, 24 bytes long.
Data: < X > D8 00 00 00 E0 58 20 00 00 00 00 00 00 00 00 00
{98} normal block at 0x00774038, 24 bytes long.
Data: < X > D8 00 00 00 E0 58 20 00 00 00 00 00 00 00 00 00
{95} normal block at 0x00774860, 24 bytes long.
Data: < X > D8 00 00 00 E0 58 20 00 00 00 00 00 00 00 00 00
Object dump complete.
24 bytes for every pthread. pthread_join()
had to free memory but it didn't. So i suppose implementation is buggy. Please confirm or confute this.
CrtSetDbgFlag
is good enough for analyze. I don't wont to debugpthreads
. It is enough to know it is buggy or I admit mistake somewhere. – Dorotheadorothee