I am writing a couple of PHP extensions as a personal project. (I used to use C professionally a few decades ago for developing realtime and process control applications, so I am a bit paranoid about always checking memory allocator returns and ensuring that error paths don’t leak memory. But then came the world of C++ and exception handlers.) Now I have a simple Q:
Do I or don’t I need to do a NULL-check on buf after:
buf = emalloc(rec->len);
Normally on a FLOSS project, I would just use the existing source as a template to answer this sort of Q, but the PHP extensions are inconsistent. Statically analysing the complex C preprocessed code is impractical, and I can only easily test my own LAMP stack. Basicially as far as I can see emalloc code does invoke zend error routines on heap exhaustion, but the code then continues and returns 0. Some extension code cases do check for NULL return, yet you also find examples such as in PHPAPI void php_basename() in ext/standard/string.c such as:
if (p_ret) {
ret = emalloc(len + 1);
memcpy(ret, comp, len);
ret[len] = '\0';
*p_ret = ret;
}
which will generate a hard memory exception if emalloc does return rather than throwing a zend exception.
If anyone knows the official PHP developer answer, I’d be grateful for this. Thanks.
The documentation clearly states: