title: Finding Memory leaks in C#
body: <p>In the following program the size of initial size of memory is not regained though garbage collection is performed. 
  1. Initial size of memory is 
  Total memory: 16,940 bytes
  Private bytes 8134656</p>
  
  <ol>
  <li><p>Created objects within a loop so that these objects are freed when gc collect is done outside the loop as these objects don't have their scope. </p></li>
  <li><p>But the memory after GC collect is not same as the initial size
  Total memory: 29,476 bytes
  Private bytes 8540160
  Handle count: 115</p></li>
  </ol>
  
  <p><p></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  
  namespace MemoryLeakTest
  {
  
      class Program
      {
          static void DisplayMemory()
          {
              Console.WriteLine("Total memory: {0:###,###,###,##0} bytes", GC.GetTotalMemory(true));            
              Console.WriteLine("Private bytes {0}", System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64);
              Console.WriteLine("Handle count: {0}", System.Diagnostics.Process.GetCurrentProcess().HandleCount);
              Console.WriteLine();
          }
  
          static void Main()
          {
              DisplayMemory();
              GC.Collect();
              for (int i = 0; i &lt; 5; i++)
              {
                  Console.WriteLine("--- New object #{0} ---", i + 1);
  
                  object o = new object();
  
                  GC.Collect();
                  DisplayMemory();
              }
              Console.WriteLine("--- press any key to quit ---");            
              Console.WriteLine();
              Console.Read();
  
              GC.Collect();
              DisplayMemory();
          }
  
      }
  }
  
  Output: 
  =======
  Total memory: 16,940 bytes
  Private bytes 8134656
  Handle count: 115
  
  --- New object #1 ---
  Total memory: 25,588 bytes
  Private bytes 8540160
  Handle count: 115
  
  --- New object #2 ---
  Total memory: 25,576 bytes
  Private bytes 8540160
  Handle count: 115
  
  --- New object #3 ---
  Total memory: 25,576 bytes
  Private bytes 8540160
  Handle count: 115
  
  --- New object #4 ---
  Total memory: 25,576 bytes
  Private bytes 8540160
  Handle count: 115
  
  --- New object #5 ---
  Total memory: 25,576 bytes
  Private bytes 8540160
  Handle count: 115
  
  --- press any key to quit ---
  
  
  Total memory: 29,476 bytes
  Private bytes 8540160
  Handle count: 115
  
  *********************************
  </code></pre>
  
  <p>What is the reason for the increase in private bytes and managed heap size from their initial size?</p>