Skip to content
Advertisement

memory_limit override isn’t causing an error when I expected

I’m creating a script that needs to exit when it hits a certain amount of memory usage. Here’s my test script:

<?php

$memory_sapper = array();
$i = 0;

while (True){
    array_push($memory_sapper, $i);
    print($i);
    print(PHP_EOL);
    print((memory_get_usage()/1024)/1024 . " Mb");
    print(PHP_EOL);
    print(memory_get_usage() . " bytes");
    print(PHP_EOL);
    if ($i == 10000){
        print("Memory Limit: " . ini_get('memory_limit'));
        print(PHP_EOL);
        exit;
    }
    $i++;
}

When I run php -d memory_limit=0.5M test.php, memory usage starts at 0.3M and grows to 0.8M. I expected the script to error around $i == 5000 but it’s not, it goes past the memory limit of 0.5M.

print("Memory Limit: " . ini_get('memory_limit')); in the script shows that the memory limit is set to 0.5M.

Even php -d memory_limit=0 test.php doesn’t keep the script from running.

If I increase $i to 100k, the script finally errors at 1.38 Mb or 1447328 bytes according to memory_get_usage. I’m unsure why it does’t error sooner. Also, the number of bytes according to memory_get_usage isn’t very close to the number of bytes recorded in the error. Here’s the error message:

PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 2097160 bytes) in ~/test.php on line 7

Any insights would be valuable. Thank you!

Advertisement

Answer

“0.5M” is not a valid value for memory_limit. If you look up memory_limit in the PHP manual, it links to this FAQ about the shorthand notation it accepts, which gives exactly that example:

Note that the numeric value is cast to int; for instance, 0.5M is interpreted as 0.

So to set to “half a megabyte”, you need to specify it in a whole number of kilobytes or bytes: memory_limit=500k or memory_limit=512000

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement