Skip to content

Zend: prevent malloc(0) in tracked allocator - #24495

Open
Sjord wants to merge 1 commit into
php:PHP-8.4from
Sjord:malloc-0-returns-null
Open

Sjord wants to merge 1 commit into
php:PHP-8.4from
Sjord:malloc-0-returns-null

Conversation

@Sjord

@Sjord Sjord commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

malloc(0) may return NULL. Prevent it by allocating at least one byte. Otherwise PHP may think the system is out of memory because malloc returns NULL.

malloc(0) may return NULL. Prevent it by allocating at least one byte.
Otherwise PHP may think the system is out of memory because malloc
returns NULL.
@devnexen

devnexen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

The only unknown would be the more exotic platforms e.g. solaris/AIX. The change is probably not enough regardless.

Edit: indeed realloc case needs to be taken in account too.

@Sjord

Sjord commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

Yes, I came to this by trying it on AIX. There malloc(0) returns NULL.

__zend_realloc already sort-of handles it:

ZEND_API void * __zend_realloc(void *p, size_t len ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
{
	p = realloc(p, len);
	if (EXPECTED(p || !len)) {
		return p;
	}
	zend_out_of_memory();
}

So when p == NULL && len == 0 it returns NULL, and does not assume it's out of memory. However, even calling realloc(..., 0) is undefined behavior in C23, so technically this is incorrect.

@devnexen

devnexen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

in that case, can this test be added ?

+--TEST--
+Zero-size reallocations with the tracked allocator
+--EXTENSIONS--
+zend_test
+--ENV--
+USE_ZEND_ALLOC=0
+USE_TRACKED_ALLOC=1
+--FILE--
+<?php
+var_dump(zend_test_erealloc_block_size(16, 0));
+var_dump(zend_test_erealloc_block_size(16, 0));
+?>
+--EXPECT--
+array(2) {
+  [0]=>
+  int(1)
+  [1]=>
+  int(1)
+}
+array(2) {
+  [0]=>
+  int(1)
+  [1]=>
+  int(1)
+}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants