title: Why does this simple php script leak memory?
body: <p>In hopes of trying to avoid future memory leaks in php programs (drupal modules, etc.) I've been messing around with simple php scripts that leak memory.</p>
  
  <p>Could a php expert help me find what about this script causes the memory usage to continually climb?</p>
  
  <p>Try running it yourself, changing various parameters. The results are interesting. Here it is:</p>
  
  <pre><code>&lt;?php
  
  function memstat() {
    print "current memory usage: ". memory_get_usage() . "\n";
  }
  
  function waste_lots_of_memory($iters) {
    $i = 0;
    $object = new StdClass;
    for (;$i &lt; $iters; $i++) {
      $object-&gt;{"member_" . $i} = array("blah blah blha" =&gt; 12345);
      $object-&gt;{"membersonly_" . $i} = new StdClass;
      $object-&gt;{"onlymember"} = array("blah blah blha" =&gt; 12345);
    }
    unset($object);
  }
  
  function waste_a_little_less_memory($iters) {
    $i = 0;
    $object = new StdClass;
    for (;$i &lt; $iters; $i++) {
  
      $object-&gt;{"member_" . $i} = array("blah blah blha" =&gt; 12345);
      $object-&gt;{"membersonly_" . $i} = new StdClass;
      $object-&gt;{"onlymember"} = array("blah blah blha" =&gt; 12345);
  
      unset($object-&gt;{"membersonly_". $i});
      unset($object-&gt;{"member_" . $i});
      unset($object-&gt;{"onlymember"});
  
    }
    unset($object);
  }
  
  memstat();
  
  waste_a_little_less_memory(1000000);
  
  memstat();
  
  waste_lots_of_memory(10000);
  
  memstat();
  </code></pre>
  
  <p>For me, the output is:</p>
  
  <pre><code>current memory usage: 73308
  current memory usage: 74996
  current memory usage: 506676
  </code></pre>
  
  <p>[edited to unset more object members]</p>