php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #53228 memory leak when throwing exception in custom handler in functions
Submitted: 2010-11-02 18:48 UTC Modified: 2012-10-25 01:17 UTC
Votes:4
Avg. Score:4.2 ± 1.3
Reproduced:3 of 4 (75.0%)
Same Version:3 (100.0%)
Same OS:3 (100.0%)
From: kgrecki at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3.3 OS: Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: kgrecki at gmail dot com
New email:
PHP Version: OS:

 

 [2010-11-02 18:48 UTC] kgrecki at gmail dot com
Description:
------------
I encountered a similar issue to #25335 where custom error handler + exceptions 
leaks memory but only when try-catch block is in a function and looped through 
directly. I imagine there's some scope/GC issues here, and whether this is actual 
bug or limitation of PHP.

Test script:
---------------
<?
set_error_handler(function($errno, $errstr, $errfile, $errline){
    throw new Exception($errstr);
});


function leak() {
    while (true) {
        try {
//            throw new Exception(); //it doesn't leak if it's thrown directly
            1 / 0; //leaks
        } catch (Exception $e) {}
        echo memory_get_usage(), PHP_EOL;
    }
}

leak();

/* it doesn't leak if it's outside of the function */
 
while (true) {
    try {
        1 / 0;
    } catch (Exception $e) {
    }
    echo memory_get_usage(), PHP_EOL;
}

/* it doesn't leak if try-catch block is in a separate function */

function foo() {
    $try = function(){
        try {1 / 0;} catch (Exception $e) {}
    };
    while (true) {
        $try();
        echo memory_get_usage(), PHP_EOL;
    }
}

foo();


Expected result:
----------------
637512
637512
637512
637512
637512
637512
...

Actual result:
--------------
639432
644272
649080
653896
658704
663512
668320
...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-11-04 17:14 UTC] uramihsayibok at gmail dot com
unset($e)ing in the catch block plugs the hole - the previous value/exception in 
$e isn't being destroyed?
 [2012-10-24 10:13 UTC] jille at hexon dot cx
This is not a bug. If you unset($e); you don't leak any memory.

It is because exceptions include a backtrace, containing all the arguments given to the error handling closure. The fifth argument given is $context, an array containing all local variables, including the previous $e.
 [2012-10-25 01:17 UTC] aharvey@php.net
-Status: Open +Status: Not a bug
 [2012-10-25 01:17 UTC] aharvey@php.net
Good explanation and catch. Closing Not A Bug.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 14 05:01:34 2025 UTC