[PATCH] malloc: Only trim on free [BZ #34882]

Wilco Dijkstra Wilco.Dijkstra@arm.com
Mon Nov 2 14:29:01 GMT 2026


Malloc may free blocks internally - currently these behave like free().
This may result in trimming which updates internal state and can result
in malloc returning NULL without running out of memory.  Remove calls to
_int_free_maybe_trim() and explicitly call it from _int_free_chunk().
This fixes BZ #34882.

Passes regress, OK for commit?

---

diff --git a/malloc/malloc.c b/malloc/malloc.c
index 3b2e4d3b4ca95283a142b4af638b119a42445931..d4d4b129a693824664b048a580a28896b426f4b1 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -821,7 +821,8 @@ typedef struct malloc_chunk* mchunkptr;
 
 static void*  _int_malloc(mstate, size_t);
 static void _int_free_chunk (mstate, mchunkptr, INTERNAL_SIZE_T);
-static void _int_free_merge_chunk (mstate, mchunkptr, INTERNAL_SIZE_T);
+static INTERNAL_SIZE_T _int_free_merge_chunk (mstate, mchunkptr,
+					      INTERNAL_SIZE_T);
 static INTERNAL_SIZE_T _int_free_create_chunk (mstate,
 					       mchunkptr, INTERNAL_SIZE_T,
 					       mchunkptr, INTERNAL_SIZE_T);
@@ -3971,11 +3972,15 @@ _int_free_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
   if (!chunk_is_mmapped(p)) {
 
     if (SINGLE_THREAD_P)
-      _int_free_merge_chunk (av, p, size);
+      {
+	size = _int_free_merge_chunk (av, p, size);
+	_int_free_maybe_trim (av, size);
+      }
     else
       {
 	__libc_lock_lock (av->mutex);
-	_int_free_merge_chunk (av, p, size);
+	size = _int_free_merge_chunk (av, p, size);
+	_int_free_maybe_trim (av, size);
 	__libc_lock_unlock (av->mutex);
       }
   }
@@ -4009,7 +4014,7 @@ _int_free_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
 /* Try to merge chunk P of SIZE bytes from locked arena AV with its neighbors.
    Put the resulting chunk on the appropriate bin list.  P must not be on a
    bin list yet, and it can be in use.  */
-static void
+static INTERNAL_SIZE_T
 _int_free_merge_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
 {
   mchunkptr nextchunk = chunk_at_offset(p, size);
@@ -4048,8 +4053,7 @@ _int_free_merge_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
     }
 
   /* Write the chunk header, maybe after merging with the following chunk.  */
-  size = _int_free_create_chunk (av, p, size, nextchunk, nextsize);
-  _int_free_maybe_trim (av, size);
+  return _int_free_create_chunk (av, p, size, nextchunk, nextsize);
 }
 
 /* Create a chunk at P of SIZE bytes, with SIZE potentially increased
@@ -4342,7 +4346,6 @@ _int_memalign (mstate av, size_t alignment, size_t bytes)
       set_head_size (p, nb);
       size = _int_free_create_chunk (av, remainder, size - nb, nextchunk,
 				     chunksize (nextchunk));
-      _int_free_maybe_trim (av, size);
     }
 
   check_inuse_chunk (av, p);




More information about the Libc-alpha mailing list