简体   繁体   中英

PHP Exception memory leak

In my console application, I replaced displaying all PHP built-in error types with throwing ErrorException :

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }

    throw new ErrorException($message, 0, $severity, $file, $line);
});

It works great, but there's one problem. Consider the following snippet:

for ($id = 1;; $id += 1) {
    try {
        $html = file_get_contents('https://stackoverflow.com/boo/' . $id);
    } catch (Exception $exception) {
        // Failed
    }
}

Every ErrorException thrown keeps the stack history. In real-life example, some IDs are missing and that causes, so after thousands of iterations, eventually the memory leak occurs.

What can be done to fix this problem? Is throwing and catching exceptions is a loop wrong? Or maybe I could disable the stacking behavior somehow?

You can unset the Exception object once you've used it on each iteration:

function getLevels($start_idx,$levels = 9){
   try {
            return $this->getBinaryTree($levels);
        } catch (Exception $e) {
            switch($e->getMessage()){
            case "Almost out of memory":
               $max_tree_depth = (int)($levels/2);
               if($max_tree_depth >= 2){
                    unset($e); // <------------------------ RIGHT HERE!
                    return $this->getLevels($start_idx,$max_tree_depth);
               }else{
                    throw new Exception("Out of memory even after getting tree with 2 levels");
               }
               break;
            default:
               throw $e;
         }
     }
}

I found the solution on the link below:

https://stuporglue.org/php-memory-leak-when-throwing-catching-and-recursing/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM