Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

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

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata