|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76778 array_reduce leaks memory if callback throws exception
Submitted: 2018-08-22 03:21 UTC Modified: 2018-08-22 11:26 UTC
From: manabu dot matsui at gmail dot com Assigned: cmb (profile)
Status: Closed Package: Arrays related
PHP Version: 7.2.9 OS:
Private report: No CVE-ID: None
 [2018-08-22 03:21 UTC] manabu dot matsui at gmail dot com
Array_reduce seems to leak memory when an exception is thrown in callback and escapes outside array_reduce.

Configure line:
./configure'  '--disable-all

I also tested it with Docker's official php image, and it was the same result. (PHP version is 7.2.8)

docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp php:7.2-cli php array_reduce-throw.php

I guess this is caused by not doing zval_ptr_dtor(&result) in the else clause of line 5977 of ext/standard/array.c. 

PR #2931( also fixes this problem, But I did not intend it when I sent it.

Test script:

for ($i = 0; $i < 1000; $i++) {
    try {
            function ($carry, $item) {
                throw new Exception;
            range(1, 200000)
    } catch (Exception $e) {

Expected result:
The test script terminates normally.

Actual result:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8388616 bytes) in /Users/matsui/array_reduce-throw.php on line 10


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-08-22 07:18 UTC]
-Status: Open +Status: Verified
 [2018-08-22 07:19 UTC]
Affects all active branches. We neglect to free the result variable in the error case.
 [2018-08-22 11:26 UTC]
-Assigned To: +Assigned To: cmb
 [2018-08-22 11:52 UTC]
Automatic comment on behalf of
Log: Fix #76778: array_reduce leaks memory if callback throws exception
 [2018-08-22 11:52 UTC]
-Status: Verified +Status: Closed
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Mon May 29 09:03:40 2023 UTC