title: Returning dynamically allocated memory back to OS without terminating the program
body: <p>I am working on a program where I am using large but limited amount of memory. Memory is allocated and freed on run time on different threads. However, I noticed that the memory usage of the program would not remain within specified bounds. It would increase as time passed on. I wrote the following sample program to check whether memory is being freed back to the OS. Half the allocated memory was freed to check if the memory usage went down.</p>
  
  <pre><code>int main()
  {
      char *p[COUNT];
  
      for(int i = 0; i &lt; COUNT; i++)
      {
          p[i] = new char[1048576];
          memset (p[i], 0, 1048576);
          printf("%p\n", p[i]);
      }
  
      printf("done allocating ... \n");
  
      sleep(10);
  
      printf("Freeing\n");
      for(int i; i &lt; COUNT; i++)
      {
          delete[] p[i];
      }
  
      while(1)
          sleep(1);
  }
  </code></pre>
  
  <p>After running the program, it seemed that the OS would not reclaim the freed pages. The memory usage remains the same as seen in "top" command in linux, after allocating and after freeing. It simply marks the pages as free for reuse by the same program.
  In my program, malloc and free are running on different threads. This poses memory management problem when malloc is called a lot more frequently than free and the process data segment grows very large, causing OS to swap pages to disk. This makes the program and OS, slow and unresponsive. Is there any way for the OS to reclaim freed memory ?</p>