[Concept,11/35] malloc: Make mcheck respect REALLOC_ZERO_BYTES_FREES

Message ID 20251210000737.180797-12-sjg@u-boot.org
State New
Headers
Series malloc: Add heap debugging commands and mcheck caller tracking |

Commit Message

Simon Glass Dec. 10, 2025, 12:07 a.m. UTC
  From: Simon Glass <simon.glass@canonical.com>

The mcheck wrapper for realloc() unconditionally frees memory and
returns NULL when size is 0. This differs from dlmalloc's default
behaviour which returns a minimum-sized allocation unless
REALLOC_ZERO_BYTES_FREES is defined.

Make the mcheck wrapper respect the same REALLOC_ZERO_BYTES_FREES
setting for consistent behavior with or without mcheck enabled.

Signed-off-by: Simon Glass <simon.glass@canonical.com>
---

 common/dlmalloc.c    | 2 ++
 test/common/malloc.c | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)
  

Patch

diff --git a/common/dlmalloc.c b/common/dlmalloc.c
index c1c9d8a8938..b46be1899f0 100644
--- a/common/dlmalloc.c
+++ b/common/dlmalloc.c
@@ -5923,11 +5923,13 @@  void dlfree(void *mem) { dlfree_impl(mcheck_free_prehook(mem)); }
 void *dlrealloc(void *oldmem, size_t bytes)
 {
 	mcheck_pedantic_prehook();
+#ifdef REALLOC_ZERO_BYTES_FREES
 	if (bytes == 0) {
 		if (oldmem)
 			dlfree(oldmem);
 		return NULL;
 	}
+#endif
 
 	if (oldmem == NULL)
 		return dlmalloc(bytes);
diff --git a/test/common/malloc.c b/test/common/malloc.c
index b114267dd83..9fdc1789645 100644
--- a/test/common/malloc.c
+++ b/test/common/malloc.c
@@ -178,7 +178,7 @@  COMMON_TEST(common_test_realloc_null, 0);
 /*
  * Test realloc() with zero size
  *
- * Standard dlmalloc behavior (without REALLOC_ZERO_BYTES_FREES or mcheck):
+ * Standard dlmalloc behavior (without REALLOC_ZERO_BYTES_FREES):
  * realloc(ptr, 0) returns a minimum-sized allocation.
  */
 static int common_test_realloc_zero(struct unit_test_state *uts)