O'Reilly logo

Programming PHP, 2nd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Memory Management

In C, you always have to worry about memory management. This still holds true when writing PHP extensions in C, but the extension API provides you with a safety net and some helpful debugging facilities if you use the API's memory-management wrapper functions (you are strongly encouraged to do so). The wrapper functions are:

    emalloc( )
    efree( )
    estrdup( )
    estrndup( )
    ecalloc( )
    erealloc( )

These work exactly like the native C counterparts after which they are named.

One of the features you get by using emalloc( ) is a safety net for memory leaks. If you emalloc( ) something and forget to efree( ) it, PHP prints a leak warning like this if you are running in debug mode (enabled by compiling PHP with the --enable-debug switch):

    foo.c(123) :  Freeing 0x0821E5FC (20 bytes), script=foo.php
    Last leak repeated 1 time

If you efree( ) something that was allocated using malloc( ) or some mechanism other than the PHP memory-management functions, you get the following:

    ---------------------------------------
    foo.c(124) : Block 0x08219C94 status:
    Beginning:      Overrun (magic=0x00000000, expected=0x7312F8DC)
          End:      Unknown
    ---------------------------------------
    foo.c(124) : Block 0x0821EB1C status:
    Beginning:      Overrun (magic=0x00000000, expected=0x7312F8DC)
          End:      Unknown
    ---------------------------------------

In this case, line 124 in foo.c is the call to efree( ). PHP knows it didn't allocate this memory because it didn't contain the magic token that indicates a PHP allocation.

The

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required