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",b-base);
    void* c= malloc(1);
    printf("Allocate c c\n%ld   %ld   %ld\n",b-base,c-base);
    free(b);
    b = malloc(1);
    printf("Free then reallocate b\n%ld   %ld   %ld\n",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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)