heap-memory - malloc 是否分配了碎片块?
问题描述
我发现有用于连续内存分配的内核驱动程序。我虽然 malloc 合并内存并返回最佳匹配,如果内存不可用,它将返回 0。如果 malloc 只分配连续内存,那么需要像 PMEM 这样的连续内存分配器。
我的问题如下
是不是因为虚拟内存没有碎片但是物理页面是碎片的?
// 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.
谢谢你。
解决方案
malloc
由于 ABI 和实现限制,glibc 会向上取整分配大小。在 64 位架构上,所有分配最终都将使用相同的内部大小。
对于您关于碎片的问题:原始 dlmalloc 代码(glibc malloc 最终基于该代码)实际上在大多数情况下确实合并了空闲块,除非在一些涉及较大应用程序的极端情况下。这并不是算法上的限制,而是不想实现某种形式的平衡树数据结构的结果。(当前的 dlmalloc 没有这个特别的限制。)
然而,多年来,glibc 在这个低级合并分配器之上分层了各种分配器。如今,有原子 fastbin 和 tcache 分配。从较低级别的分配器的角度来看,这些仍然在使用中,因此它们不能与相邻的分配合并。
推荐阅读
- c - C 语言中的 while(*pointer) 合法吗?
- r - R:函数工厂的管道输入
- php - 该页面无法处理请求。在本地主机上运行 php
- javascript - Javascript 运行时是否缓存/优化嵌套对象访问?
- laravel - 给定邮箱中的地址 [test@gmail.com,test1@gmail.com] 不符合 RFC 2822, 3.6.2 laravel
- reactjs - React.js + asp.net core + windows 集成单点登录
- c - 终端如何跟随我的编辑器的大小调整?
- python - 比较两个字符串是否相等的超快速方法
- python - 将多个函数的列表作为参数传递给另一个 python 函数
- c# - Blazor 客户端引导选择不起作用