runsisi's

technical notes

libc free

2019-09-14 runsisi#coding#cpp

glibc

# define MADV_DONTNEED    4 /* Don't need these pages.  */
# define MADV_FREE    8 /* Free pages only if memory pressure.  */
malloc_trim
    __malloc_trim
        mtrim
            __madvise(..., MADV_DONTNEED)

tcmalloc

#include <gperftools/malloc_extension.h>

MallocExtension::instance()->ReleaseFreeMemory();
    TCMallocImplementation::ReleaseToSystem
        PageHeap::ReleaseAtLeastNPages
            PageHeap::ReleaseSpan
                PageHeap::DecommitSpan
                    TCMalloc_SystemRelease
                        madvise(..., MADV_FREE)

jemalloc

export MALLOC_CONF="background_thread:true"

mimalloc

static mi_option_desc_t options[_mi_option_last] =
{
  { 0, UNINIT, "page_reset" },
};

mi_collect
    mi_heap_collect
        mi_heap_collect_ex
            mi_heap_page_collect
                _mi_page_free
                    _mi_segment_page_free
                        mi_segment_page_clear
                            _mi_mem_reset
                                _mi_os_reset
                                    mi_os_resetx
            _mi_mem_collect
                _mi_os_free
                    mi_os_mem_free
                        munmap

mi_os_resetx
    static int advice = MADV_FREE;
    int err = madvise(start, csize, advice);
    if (err != 0 && errno == EINVAL && advice == MADV_FREE) {
        // if MADV_FREE is not supported, fall back to MADV_DONTNEED from now on
        advice = MADV_DONTNEED;
        err = madvise(start, csize, advice);
    }

参考资料

Use jemalloc by default?

https://bugs.ruby-lang.org/issues/14718

Force free() to return malloc memory back to OS

https://stackoverflow.com/questions/27945855/force-free-to-return-malloc-memory-back-to-os

mm: support madvise(MADV_FREE)

https://lwn.net/Articles/590693/

glibc allocator doesn’t release all free()ed memory

https://bugs.python.org/issue11849

what does “malloc_trim(0)” really mean?

https://stackoverflow.com/questions/15529643/what-does-malloc-trim0-really-mean

regression? v5.1 doesn’t seem to release memory back to the OS?

https://github.com/jemalloc/jemalloc/issues/1398

Testing Memory Allocators: ptmalloc2 vs. tcmalloc vs. hoard vs. jemalloc

https://news.ycombinator.com/item?id=17457699