In depth analysis of the handling of memory leaks by PHP garbage collection mechanism

  • 2020-06-15 07:50:51
  • OfStack

Last time we talked about refcount and is_ref, here are the memory leaks


$a = array(1, 2, &$a);
unset($a);

In the old VERSION of PHP, there was a memory leak and the analysis was as follows:

By executing line 1, you know that $a and $a[2] point to zval refcount=2, is_ref=1

Then execute line 2, $a will be deleted from the symbol table, pointing to zval's refcount--, at which point refcount=1 because refcount! =0, so zval is not garbage collected, but at this point we lose $a[2] pointing to the entrance to the zval, so the zval becomes a block of memory garbage

The same thing can happen with intra-class references, for example


$a = new Man();
$a->self = &$a;
unset($a);

So how to solve this problem, the new GC mechanism USES 1 algorithm to solve this problem

PHP has one root buffer to store the node information of zval. When root buffer is full or the gc function is called manually, the GC algorithm starts

For zval an array or class type, garbage collection at startup, algorithms for the zval internal elements of the array/class/member zval one traversal and refcount minus 1, if after the completion of the traverse the zval refcount was reduced to zero, then the zval is a memory of garbage, he will be destroyed, see the example below


$a = array(1, 2, &$a, &$a);
unset($a);

It is easy to know which zval $a points to, assuming that refcount=3 and is_ref=1

When unset($a) executes, $a is deleted from the symbol table and we lose the entry to z1, z1 refcount=2, is_ref=1

When GC is started, the zval refcount of the array element of z1 is traversed minus 1. When a[2] is traversed,z1 refcount--, a[3] is z1 refcount--, at this time, z1 refcount = 0, z1 can be marked as memory garbage, and the algorithm will recycle it

To sum up, if an zval of array type is traversed once to its element zval, then the traversal to refcount of zval --, if refcount=0 is zval, it is garbage and needs to be recycled


Related articles: