What is memory leak in php?

I've encountered the dreaded error-message, possibly through-painstaking effort, PHP has run out of memory:

Allowed memory size of #### bytes exhausted [tried to allocate #### bytes] in file.php on line 123

Increasing the limit

If you know what you're doing and want to increase the limit see memory_limit:

ini_set['memory_limit', '16M'];
ini_set['memory_limit', -1]; // no limit

Beware! You may only be solving the symptom and not the problem!

Diagnosing the leak:

The error message points to a line withing a loop that I believe to be leaking, or needlessly-accumulating, memory. I've printed memory_get_usage[] statements at the end of each iteration and can see the number slowly grow until it reaches the limit:

foreach [$users as $user] {
    $task = new Task;
    $task->run[$user];
    unset[$task]; // Free the variable in an attempt to recover memory
    print memory_get_usage[true]; // increases over time
}

For the purposes of this question let's assume the worst spaghetti code imaginable is hiding in global-scope somewhere in $user or Task.

What tools, PHP tricks, or debugging voodoo can help me find and fix the problem?

asked May 11, 2009 at 19:04

Mike BMike B

31.6k13 gold badges85 silver badges111 bronze badges

1

PHP doesn't have a garbage collector. It uses reference counting to manage memory. Thus, the most common source of memory leaks are cyclic references and global variables. If you use a framework, you'll have a lot of code to trawl through to find it, I'm afraid. The simplest instrument is to selectively place calls to memory_get_usage and narrow it down to where the code leaks. You can also use xdebug to create a trace of the code. Run the code with execution traces and show_mem_delta.

answered May 11, 2009 at 19:44

troelskntroelskn

112k24 gold badges132 silver badges154 bronze badges

8

Here's a trick we've used to identify which scripts are using the most memory on our server.

Save the following snippet in a file at, e.g., /usr/local/lib/php/strangecode_log_memory_usage.inc.php:

Chủ Đề