Bug #71737 [Opn]: Memory leak in closure with parameter named $this
| From: | james dot harris at icecave dot com dot au | Date: | Sun, 13 Mar 2016 02:19:16 +0000 |
| Subject: | Bug #71737 [Opn]: Memory leak in closure with parameter named $this | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-199784@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=71737&edit=1
ID: 71737
User updated by: james dot harris at icecave dot com dot au
Reported by: james dot harris at icecave dot com dot au
Summary: Memory leak in closure with parameter named $this
Status: Open
Type: Bug
Package: Scripting Engine problem
Operating System: OSX
PHP Version: 7.0.4
Block user comment: N
Private report: N
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2016-03-11 23:07:49] nikic@php.net
I agree with @bwoebi, this should be forbidden.
------------------------------------------------------------------------
[2016-03-08 07:10:48] 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-08 05:38:00] 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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=71737&edit=1