title: Detached pthreads and memory leak
body: <p>Can somebody please explain to me why this simple code leaks memory?</p>
  
  <p>I believe that since pthreads are created with detached state their resources should be released inmediatly after it's termination, but it's not the case.</p>
  
  <p>My environment is Qt5.2.</p>
  
  <pre><code>#include &lt;QCoreApplication&gt;
  #include &lt;windows.h&gt;
  
  void *threadFunc( void *arg )
      {
      printf("#");
      pthread_exit(NULL);
      }
  
  int main()
      {
      pthread_t thread;
      pthread_attr_t attr;
  
      while(1)
          {
          printf("\nStarting threads...\n");
          for(int idx=0;idx&lt;100;idx++)
              {
              pthread_attr_init(&amp;attr);
              pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_DETACHED);
              pthread_create( &amp;thread, &amp;attr, &amp;threadFunc, NULL);
              pthread_attr_destroy ( &amp;attr );
              }
          printf("\nSleeping 10 seconds...\n");
          Sleep(10000);
          }
      }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/0Gqki.png" alt="Memory leak graph"></p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I discovered that if I add a slight delay of 5 milliseconds inside the <code>for</code> loop the leak is <strong>WAY</strong> slower:</p>
  
  <pre><code>    for(int idx=0;idx&lt;100;idx++)
          {
          pthread_attr_init(&amp;attr);
          pthread_attr_setdetachstate(&amp;attr, PTHREAD_CREATE_DETACHED);
          pthread_create( &amp;thread, &amp;attr, &amp;threadFunc, NULL);
          pthread_attr_destroy ( &amp;attr );
          Sleep(5); /// &lt;--- 5 MILLISECONDS DELAY ///
          }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/XP5RD.png" alt="Memory leak graph with slight delay">
  This is freaking me out, could somebody please tell me what is happening? How this slight delay may produce such a significant change? (or alter the behavior in any way)</p>
  
  <p>Any advice would be greatly appreciated.</p>
  
  <p>Thanks.</p>
  
  <p><strong>UPDATE2:</strong></p>
  
  <p>This leak was observed on Windows platforms (W7 and XP), no leak was observed on Linux platforms (thank you @MichaelGoren)</p>