php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71737 Memory leak in closure with parameter named $this
Submitted: 2016-03-08 05:38 UTC Modified: 2016-03-13 02:19 UTC
Votes:2
Avg. Score:3.5 ± 1.5
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:0 (0.0%)
From: james dot harris at icecave dot com dot au Assigned:
Status: Closed Package: Scripting Engine problem
PHP Version: 7.0.4 OS: OSX
Private report: No CVE-ID:
 [2016-03-08 05:38 UTC] james dot harris at icecave dot com dot au
Description:
------------
A memory leak occurs when a closure that is defined inside a class and has a parameter named $this is invoked with a value that contains a reference to $this.

This gist (https://gist.github.com/jmalloc/e3db5842c2c4ab2a1edf) might help explain a little better.

Affected PHP versions: https://3v4l.org/lr963

Test script:
---------------
class MemoryLeak
{
    public function bad()
    {
        $closure = function ($this) {};
        $closure([$this]);
    }
}

$object = new MemoryLeak;
ini_set('memory_limit', '10M');

for ($i = 0; $i < 1000000; ++$i) {
    $object->bad();
}

echo "Done" . PHP_EOL;

Expected result:
----------------
Done

Actual result:
--------------
Fatal error: Allowed memory size of 10485760 bytes exhausted (tried to allocate 4096 bytes) in /Users/james/<snip>/leak.php on line 8


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-03-08 07:10 UTC] bwoebi@php.net
This should be just outright forbidden as Closures may be bound to a $this and we generally do prevent $this overloading in methods.

php -r 'class a { function b($this) {} } (new a)->b(1);'
PHP Fatal error:  Cannot re-assign $this in Command line code on line 1
 [2016-03-11 23:07 UTC] nikic@php.net
I agree with @bwoebi, this should be forbidden.
 [2016-03-13 02:19 UTC] james dot harris at icecave dot com dot au
I would hope this is very uncommon, but I did encounter it in the wild with code that was fine under PHP 5. That said, I agree absolutely that it should be forbidden, for whatever that's worth.
 [2016-04-20 16:47 UTC] nikic@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=77bb96d7c95ddfdba8b16325db439913ee58522f
Log: Fix bug #71737
 [2016-04-20 16:47 UTC] nikic@php.net
-Status: Open +Status: Closed
 [2016-05-26 20:03 UTC] nino dot skopac at gmail dot com
Yes, I give you permission to make it forbidden.
 [2016-07-20 11:32 UTC] davey@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=77bb96d7c95ddfdba8b16325db439913ee58522f
Log: Fix bug #71737
 
PHP Copyright © 2001-2017 The PHP Group
All rights reserved.
Last updated: Tue Feb 21 14:01:44 2017 UTC