title: std::string memory management
body: <p>I have problem with memory management with std::string.</p>
  
  <p>I have application - multithread server with detached threads (i done need to join them, they will do the job and exit) and i found that after a while memory usage comes quite high. I've started to experiment where is the problem and i've created test program which demonstrating the problem</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  #include &lt;string&gt;
  #include &lt;pthread.h&gt;
  
  pthread_t           thread[100];
  
  using namespace std;
  
  class tst {
      public:
          tst() {
              //cout &lt;&lt; "~ Create" &lt;&lt; endl;
          }
          ~tst() {
              //cout &lt;&lt; "~ Delete" &lt;&lt; endl;
          }
          void calc() {
              string TTT;
              for (int ii=0; ii&lt;100000; ii++) {
                  TTT+="abcdenbsdmnbfsmdnfbmsndbfmsndb ";
              }
          }
  };
  
  void *testThread (void *arg) {
      int cnt=*(int *) arg;
      cout &lt;&lt; cnt &lt;&lt; " ";
      tst *TEST=new tst;
      TEST-&gt;calc();
      delete TEST;
      pthread_exit((void *)0);
  }
  
  int main (int argc, char * const argv[]) {
  
  cout &lt;&lt; "---------------------------------------------------" &lt;&lt; endl;
  sleep(5);
  
      for (int oo=0; oo&lt;100; oo++) {
          pthread_create(&amp;thread[oo], NULL, testThread, &amp;oo);
          pthread_detach(thread[oo]);
      }
      cout &lt;&lt; endl;
      cout &lt;&lt; "---------------------------------------------------" &lt;&lt; endl;
  
      sleep(5);
  
      for (int oo=0; oo&lt;100; oo++) {
          pthread_create(&amp;thread[oo], NULL, testThread, &amp;oo);
          pthread_detach(thread[oo]);
      }
      cout &lt;&lt; endl;
      cout &lt;&lt; "---------------------------------------------------" &lt;&lt; endl;
  
      sleep(5);
      exit(0);
  }
  </code></pre>
  
  <p>after first "---" the memory usage is 364KB, after second its 19MB, after third is 33.5MB.
  there is 1 strange thing as well - each run showing different memory usage but mostly the last memory usage is about 50% more then after the second "---".</p>
  
  <p>i've expected that if the class TEST (tst) is deleted then the string will release its memory as well - i found that threads will not do that - that's why i'm creating new tst, running it and then delete.</p>
  
  <p>in my program this causing a big problem because i'm using there few strings in each thread and after a while the memory usage is over gig ;-(</p>
  
  <p>is there any option how to 'empty' the memory after string?</p>
  
  <p>i've tried TTT="" or TTT.clear() without any change.</p>
  
  <p>...i need to use threads - it will be running on multicpu machine where threads is the only option to use it's 'full power' (as i know)</p>