How to Manage Memory in PHP | WebReference

How to Manage Memory in PHP

current pageTo page 2To page 3To page 4
[next]

How to Manage Memory in PHP

This Chapter is excerpted from the new book titled, "Extending and Embedding PHP", authored by Sara Golemon, published by Sams in the Developer's Library, May, 2006. Copyright 2006 by Sams Publishing. All rights reserved, reprinted with permission from Pearson Education. Content excerpt represents Chapter 3, pages 35 to 46. To learn more, please visit: www.samspublishing.com/title/067232704x

Chapter 3: Memory Management

ONE OF THE MOST JARRING DIFFERENCES BETWEEN A MANAGED language like PHP, and an unmanaged language like C is control over memory pointers.

Memory

In PHP, populating a string variable is as simple as <?php $str = ‘hello world’; ?> and the string can be freely modified, copied, and moved around. In C, on the other hand, although you could start with a simple static string such as char *str = "hello world";, that string cannot be modified because it lives in program space. To create a manipulable string, you'd have to allocate a block of memory and copy the contents in using a function such as strdup().

For reasons you'll explore through the course of this chapter, the traditional memory management functions (malloc(), free(), strdup(), realloc(), calloc(), and so on) are almost never used directly by the PHP source code.

Free the Mallocs

Memory management on nearly all platforms is handled in a request and release fashion. An application says to the layer above it (usually the operating system) "I want some number of bytes of memory to use as I please." If there is space available, the operating system offers it to the program and makes a note not to give that chunk of memory out to anyone else.

When the application is done using the memory, it's expected to give it back to the OS so that it can be allocated elsewhere. If the program doesn't give the memory back, the OS has no way of knowing that it's no longer being used and can be allocated again by another process. If a block of memory is not freed, and the owning application has lost track of it, then it's said to have "leaked" because it's simply no longer available to anyone.

In a typical client application, small infrequent leaks are sometimes tolerated with the knowledge that the process will end after a short period of time and the leaked memory will be implicitly returned to the OS. This is no great feat as the OS knows which program it gave that memory to, and it can be certain that the memory is no longer needed when the program terminates.

With long running server daemons, including web servers like Apache and by extension mod_php, the process is designed to run for much longer periods, often indefinitely. Because the OS can't clean up memory usage, any degree of leakage—no matter how small—will tend to build up over time and eventually exhaust all system resources. Consider the userspace stristr() function; in order to find a string using a case-insensitive search, it actually creates a lowercase copy of both the haystack and the needle, and then performs a more traditional case-sensitive search to find the relative offset. After the offset of the string has been located, however, it no longer has use for the lowercase versions of the haystack and needle strings. If it didn't free these copies, then every script that used stristr() would leak some memory every time it was called. Eventually the web server process would own all the system memory, but not be able to use it.

The ideal solution, I can hear you shouting, is to write good, clean, consistent code, and that's absolutely true. In an environment like the PHP interpreter, however, that's only half the solution.

Error Handling

In order to provide the ability to bail out of an active request to userspace scripts and the extension functions they rely on, a means needs to exist to jump out of an active request entirely. The way this is handled within the Zend Engine is to set a bailout address at the beginning of a request, and then on any die() or exit() call, or on encountering any critical error (E_ERROR) perform a longjmp() to that bailout address.

Although this bailout process simplifies program flow, it almost invariably means that resource cleanup code (such as free() calls) will be skipped and memory could get leaked. Consider this simplified version of the engine code that handles function calls:

When the php_error_docref() line is encountered, the internal error handler sees that the error level is critical and invokes longjmp() to interrupt the current program flow and leave call_function() without ever reaching the efree(lcase_fname) line. Again, you're probably thinking that the efree() line could just be moved above the zend_error() line, but what about the code that called this call_function() routine in the first place? Most likely fname itself was an allocated string and you can't free that before it has been used in the error message.

Note: The php_error_docref() function is an internals equivalent to trigger_error(). The first parameter is an optional documentation reference that will be appended to docref.root if such is enabled in php.ini. The third parameter can be any of the familiar E_* family of constants indicating severity. The fourth and later parameters follow printf() style formatting and variable argument lists.

 

Created: March 27, 2003
Revised: June 19, 2006

URL: https://webreference.com/programming/php_mem/1