PHP’s API for allocating memory from the heap is almost identical to the stan-
dard C API. When writing extensions, use the following API functions that
correspond to their C counterparts (and therefore are not explained):
emalloc(size_t size);
efree(void *ptr);
ecalloc(size_t nmemb, size_t size);
erealloc(void *ptr, size_t size);
estrdup(const char *s);
estrndup(const char *s, unsigned int length);
At this point, any experienced C developer should be thinking something
like, “What? strndup() doesn’t exist in standard C?” Well, that is correct
because it is a GNU extension typically available on Linux. estrndup() is the
only function that is special to PHP. It behaves like estrdup(), but you can
specify the length of the string you want to duplicate (without the terminating
null) and is, therefore, binary safe. This is recommended over estrdup().
Under almost all circumstances, you should use these allocation func-
tions. There are some cases where extensions need to create memory that will
be persistent in between requests where regular malloc() has to be used, but
unless you know what you are doing, you should always use these functions.
PHP will crash if you return values into the scripting engine that are not allo-
cated with these functions, but with their standard C counterparts.
Advantages of these functions are that any such allocated memory that is
accidentally not freed will be released at the end of a request. Therefore, it can’t
cause real memory leaks. However, don’t rely on this, and make sure you free
memory when you are supposed to–both for debugging and performance rea-
sons. Other advantages include improved performance in multi-threaded envi-
ronments, detection of memory corruption in debug mode, and more.
Another important point to mention is that you don’t have to check the
return values of the memory allocation functions for null. When memory allo-
cation fails, they will bail out with an E_ERROR and will, therefore, never return.
