Memory leakage in windows pthread. `pthread_join` does not deallocate memory
Asked Answered
D

1

0

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.

Dorotheadorothee answered 9/12, 2016 at 9:56 Comment(0)
Z
1

If you want to track down the allocation point see _CrtSetAllocHook - you can set your own allocation hook and examine the stack for the blocks you know that will be leaked. However for this to bring any benefits you would need a debug version of the POSIX implementation to correctly see the stack. Then you can try and actually patch it so that the memory is freed.

Zakaria answered 9/12, 2016 at 10:40 Comment(2)
I think CrtSetDbgFlag is good enough for analyze. I don't wont to debug pthreads. It is enough to know it is buggy or I admit mistake somewhere.Dorotheadorothee
@Dorotheadorothee well if you want to sort out your mistakes then CrtSetAllocHook will show if the faulty memory blocks are allocated from your stack or from the pthreads library.Zakaria

© 2022 - 2024 — McMap. All rights reserved.