phpinternalsbook / PHP-Internals-Book

PHP Internals Book
http://www.phpinternalsbook.com/
Other
1.39k stars 177 forks source link

Document that `free()`-style functions are expected to be safe when passing `NULL` #139

Open TimWolla opened 1 year ago

TimWolla commented 1 year ago

see https://github.com/php/php-src/pull/10246#pullrequestreview-1241037537

mvorisek commented 1 year ago

linux free support such behaviour for BC reasons, I actually prefer stricter approach - never call freeXxx twice, calling free multiple time can imply hidden issue and/or performance issue

IIRC, this is also how some libs like Sqlite are tested - https://www.sqlite.org/malloc.html#memdebug

TimWolla commented 1 year ago

The behavior of free(NULL) is well-defined to be a noop in POSIX, checking the pointer against NULL yourself before calling free is just redundant.

It appears you are confusing a double free (“call free twice”) with freeing a NULL pointer. One specifically sets a freed pointer to NULL to reduce the chance of a double free happening.

mvorisek commented 1 year ago

You are right, even in very strict Sqlite tests free(NULL) (and freeXxx(NULL) in general) is fine. 👍