首页 > 解决方案 > 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

标签: cdata-structures

解决方案


推荐阅读