[Bug malloc/14581] memalign allocations are often not reused after free

henri at henrimenke dot de via Glibc-bugs <[email protected]> Thu, 23 Jul 2026 16:22:13 +0000
Newsgroups gmane.comp.lib.glibc.bugs
Message-ID <[email protected]/bugzilla/>
https://sourceware.org/bugzilla/show_bug.cgi?id=3D14581

Henri Menke <henri at henrimenke dot de> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |henri at henrimenke dot de

--- Comment #26 from Henri Menke <henri at henrimenke dot de> ---
From playing around a little bit and having a look at the code this is my t=
ake:
 Very small allocations go into the tcache and are always perfectly reused,
because when aligned memory is requested, the tcache is scanned linearly un=
til
a matching chunk is found.  Allocations larger than the mmap threshold are
never reused, but that is by design.  For intermediate allocations the logic
fails.

When an aligned allocation is requested, the allocation is padded by MINSIZE
and rounded up to the alignment.  Then the excess is split into a separate
chunk that is freed immediately and the aligned chunk is returned.  Any
subsequent *identical* aligned allocation will not be able to reuse the
previous chunk, because any information about alignment has been trimmed and
the chunk looks just like any other (in particular it's missing MINSIZE and
alignment).

This would be fixable by scanning all chunks for one with matching size and
alignment, but in contrast to the tcache this is unbounded.  Another possib=
le
fix is to keep the information that the chunk is aligned in the header and =
also
not trim the alignment, but this leads to an internal fragmentation of up to
alignment + MINSIZE per live allocation, which is fine for small alignment =
but
disastrous for, e.g. alignment at page boundary.

For the latter case of keeping a shadow header, I have included a rather cr=
ude
patch that explores this direction.  This could (and should) be improved to
only keep the shadow header when the ratio of wasted space to total allocat=
ion
size is small and probably also be hidden behind some kind of tunable.  Sin=
ce I
am not at all familiar with developing memory allocators, I would be very h=
appy
if the experts coul share their opinion on this.

Kind regards,
Henri

--=20
You are receiving this mail because:
You are on the CC list for the bug.=