[Concept,11/37] malloc: return NULL if not initialized yet

Message ID 20251201170529.3237986-12-sjg@u-boot.org
State New
Headers
Series malloc: Import dlmalloc 2.8.6 |

Commit Message

Simon Glass Dec. 1, 2025, 5:04 p.m. UTC
  From: Simon Glass <simon.glass@canonical.com>

When malloc() was called before it was properly initialized
(as would happen if when used before relocation to RAM) it returned
random, non-NULL values, which called all kinds of difficult to debug
subsequent errors.

Make sure to return NULL when initialization was not done yet.

Signed-off-by: Simon Glass <simon.glass@canonical.com>
(cherry picked from commit 2740544881f652566756815dda4da0bcd946e9de)
---

 common/dlmalloc.c | 5 +++++
 1 file changed, 5 insertions(+)
  

Patch

diff --git a/common/dlmalloc.c b/common/dlmalloc.c
index ff13a779211..baa9b500e10 100644
--- a/common/dlmalloc.c
+++ b/common/dlmalloc.c
@@ -4582,6 +4582,11 @@  static void* tmalloc_small(mstate m, size_t nb) {
 #if !ONLY_MSPACES
 
 void* dlmalloc(size_t bytes) {
+#ifdef __UBOOT__
+  /* Return NULL if not initialized yet */
+  if (!mem_malloc_start && !mem_malloc_end)
+    return NULL;
+#endif
   /*
      Basic algorithm:
      If a small request (< 256 bytes minus per-chunk overhead):