首页 > 解决方案 > malloc 是否分配了碎片块?

问题描述

我发现有用于连续内存分配的内核驱动程序。我虽然 malloc 合并内存并返回最佳匹配,如果内存不可用,它将返回 0。如果 malloc 只分配连续内存,那么需要像 PMEM 这样的连续内存分配器。

我的问题如下

  1. 是不是因为虚拟内存没有碎片但是物理页面是碎片的?

// Assuming we have 20bytes of heap(excluding malloc header information)
p1 = malloc(4)
p2 = malloc(3)
p3 = malloc(3)
p4 = malloc(10) // total 20bytes allocd
free(p2)
free(p4) // free 10 + 3 = 13.
malloc(13)????? // Would this fail because of no large enough chunk or does it fragment?
// If it allocates where in the malloc header or payload does it store the next chunk information.

谢谢你。

标签: heap-memoryglibcmemory-fragmentation

解决方案


malloc由于 ABI 和实现限制,glibc 会向上取整分配大小。在 64 位架构上,所有分配最终都将使用相同的内部大小。

对于您关于碎片的问题:原始 dlmalloc 代码(glibc malloc 最终基于该代码)实际上在大多数情况下确实合并了空闲块,除非在一些涉及较大应用程序的极端情况下。这并不是算法上的限制,而是不想实现某种形式的平衡树数据结构的结果。(当前的 dlmalloc 没有这个特别的限制。)

然而,多年来,glibc 在这个低级合并分配器之上分层了各种分配器。如今,有原子 fastbin 和 tcache 分配。从较低级别的分配器的角度来看,这些仍然在使用中,因此它们不能与相邻的分配合并。


推荐阅读