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.

Community
  • 1
  • 1
kyb
  • 7,233
  • 5
  • 52
  • 105

1 Answers1

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.

Rudolfs Bundulis
  • 11,636
  • 6
  • 33
  • 71
  • 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. – kyb Dec 09 '16 at 10:56
  • @kyb 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. – Rudolfs Bundulis Dec 09 '16 at 11:06