Subject: bug#45200: [PATCH] Force Glibc to free the memory freed

From: DJ Delorie <[email-masked]>
Date: Wed, 03 Feb 2021 15:51:51 -0500

Konstantin Kharlamov <[email-masked]> writes:
> α) sometimes, call to `free()` frees memory completely
> β) sometimes, call to `free()` leaves memory lingering forever, till malloc_trim is called additionally.
>
> The answer I'd like to know is why do you not do always either α or
> always β? (I'm leaving out here the question of which way is correct
> and why, I'm rather curious just why the difference in behavior).

If the chunk being free'd happens to be the highest-addressed chunk in
the heap, it "exposes" that hole in the heap below it, if that exceeds
MALLOC_TRIM_THRESHOLD it causes a trim.

If the chunk is *not* at the top of the heap, nothing happens.  We only
trim the top of the heap.

Of course, this assumes that the caching logic doesn't decide to hold on
to the chunk *anyway* (like, if it's put in tcache), in which case it's
not freed despite being at the top of the heap.  Note that any patch
affecting tcache performance will need to be vigorously defended ;-)

IIRC the fastbin cache also holds onto the top chunk.  Since trimming
cleans the fastbin, this often frees the top chunk.  Disabling fastbins
might be an interesting thing to try.