c - malloc和free的机制
问题描述
我正在研究 C 中 malloc() 和 free() 函数的机制。经过几次测试,我发现这些函数的机制遵循最差拟合算法,不是吗。
#include <stdio.h>
#include <stdlib.h>
int main()
{
void* base;
void* a = malloc(100);
base = a;
void* b = malloc(60);
printf("%ld %ld\n", a-base, b-base);
free(a);
a = malloc(40);
printf("Free then reallocate a\n%ld %ld\n", a-base, b-base);
void* c= malloc(1);
printf("Allocate c c\n%ld %ld %ld\n", a-base, b-base, c-base);
free(b);
b = malloc(1);
printf("Free then reallocate b\n%ld %ld %ld\n", a-base, b-base, c-base);
return 0;
}
输出:
0 112
Free then reallocate a
720 112
Allocate c c
720 112 768
Free then reallocate b
720 800 768
解决方案
推荐阅读
- c++ - RWStructuredBuffer 计数器不递减 (DX12)
- algorithm - 计算两个排列中的对 (a,b),使得两个排列中的 index(a) < index(b)
- c++ - 在复制构造函数定义中调用成员构造函数
- javascript - 计算器退格按钮
- html - 内联块的父级不是其子级的宽度,即使其父级是溢出隐藏的
- javascript - 如何替换空格并从对象的所有键中删除特殊字符
- video-streaming - 在 RTSP 流中提供特殊字符密码
- android - 不推荐使用 setCellType(CellType.STRING)
- swift5.2 - 如何解决 Swift 5.2 中的“Inout 表达式创建临时指针”问题?
- android - 如何优化 Kotlin 中 Context、Fragment 和 Activity 的扩展功能代码?