malloc 的底层实现
1. 当你malloc()一块很小的内存是, glibc调用brk(), 只需要在heap中移动一下指针, 即可获得可用虚存, 这样分配得到的地址较小.
2. 当你malloc()一块较大内存时, glibc调用mmap(), 需要在内核中重新分配vma结构等, 他会在靠近栈的地方分配虚存, 这样返回的地址大.
3. 这个较小和较小的临界值是一个通过mallopt()调整的. mallopt(M_MMAP_THRESHOLD, 内存块大小), 这样只有超过这个"内存块大小"的malloc才会使用mmap(), 其他使用brk, 使用brk()从贴近heap的地方开始分配. M_MMAP_THRESHOLD=128K (default)
4. 当然, 除了上面的规则, malloc()还有自己的算法, 来判断到底采用mmap()还是brk(), 一般和虚存碎片有关.
malloc的上层实现
glibc中的malloc实现:
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.
Advanced Memory Allocation
malloc实现原理 -- 参考帖子
http://blog.csdn.net/vincent_smz/article/details/6338417
http://blog.csdn.net/haoel/article/details/6338025
http://www.douban.com/note/146145117/
glibc中malloc的详细解释