Search code examples
c++cglibc

Why does malloc_trim() only work with the main arena?


glibc's malloc implementation supports 'malloc_trim()' call that lets an application program release unused(ie freed memory chunks) back to the system(implementation detail: the data segment of the program is reduced by calling sbrk() with a negative argument). However, this function only works with the main arena. In multithreaded programs, there are multiple arenas that hold freed chunks. Why does this call not release memory from the other arenas as well?


Solution

  • Arenas other than the main one are probably allocated from the system using mmap so sbrk cannot be used to return that memory to the system. It could be possible to make glibc use mremap to shrink these other arenas. Note also that malloc_trim can only return memory at the end of the arena, if there are empty blocks in the middle of the arena there's no way to release that memory.