开发者

How to intentionally cause a "Fatal error: Allowed memory size of xxx bytes exhausted"

Whenever I've received this error, I just increased the memory to fix it. I have a case where, for testing purposes, I want to cause a page to use up all the memory however big I set the memory_limit.

I have no idea how to go about doing that.

EDIT: I tried this:

<?php
echo "start";
@ini_set('memory_limit', '1M');
$test = "a";
while (1) {
    $test = "a" + $test;    
}
echo "done";
?>

But it didn't crash. At the end it just printed "startstart" which is strange that it was printed twice...

I'd like a simple code e开发者_JAVA百科xample, the "put a lot of stuff in memory".. well I know that much.


Should eat all memory.

$a = 'x';
while (true) {
    $a = $a.$a;
}


Here's the problem:

$test = "a" + $test;

+ in PHP is for arithmetic, not string concatination. Use:

$test = "a" . $test;


str_pad("",PHP_INT_MAX);


You can do an infinite loop, although I would advise against that.

You can also open / read into memory big files that would exceed the memory limit, you could also write a loop that would generate a string with the amount of bytes which would exceed the memory limit.

Which is best, no clue. But there are a couple options available to you.


  1. Download all Google Maps images.
  2. Then re-size them using GD into a 1-1 scale.


Write a PHP function that tries to find a pattern within /dev/random


<?php
$limit = ini_get('memory_limit');
$last = strtolower($limit[strlen($limit)-1]);
switch($last) {
    case 'g':
        $limit *= 1024;
    case 'm':
        $limit *= 1024;
    case 'k':
        $limit *= 1024;
}
$limit = $limit + 1;//not needed actually, I assume the script has consumed 1 byte of memory by now...
$foo = `dd if=/dev/zero bs=$limit count=1`;
//or, if you don't like the command line:
$bar = str_repeat($a,$limit);


I like simple solutions so I often just to this line which works like a charm.

str_repeat('a', PHP_INT_MAX);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜