libc malloc vs linux 内核伙伴分配器

libc malloc vs linux kernel buddy allocator

malloc 是否担心 linux 内核中的内部碎片? 例如,当我想分配 5 个页面时,malloc 会向上舍入大小使其成为 2 的幂:5->8 以避免内核中的内部碎片,因为 linux 内核使用伙伴系统作为页面分配器。

至少对于 glibc 来说,它并不真正关心内核中的碎片。它主要是一个 "best-fit" 分配器,除了非常小或非常大的分配。这是 glibc 的“malloc.c”顶部附近评论的摘录:

  • Why use this malloc?

    This is not the fastest, most space-conserving, most portable, or most tunable malloc ever written. However it is among the fastest while also being among the most space-conserving, portable and tunable. Consistent balance across these factors results in a good general-purpose allocator for malloc-intensive programs. The main properties of the algorithms are:

    • For large (>= 512 bytes) requests, it is a pure best-fit allocator, with ties normally decided via FIFO (i.e. least recently used).
    • For small (<= 64 bytes by default) requests, it is a caching allocator, that maintains pools of quickly recycled chunks.
    • In between, and for combinations of large and small requests, it does the best it can trying to meet both goals at once.
    • For very large requests (>= 128KB by default), it relies on system memory mapping facilities, if supported.

    For a longer but slightly out of date high-level description, see http://gee.cs.oswego.edu/dl/html/malloc.html

glibc malloc 实现可以使用 mallopt 函数或各种环境变量来设置各种参数,如手册页 mallopt(3) 中所述。