linux堆-first_fit内存分配

first_fit

实例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char* a = malloc(512);
char* b = malloc(256);
char* c;
fprintf(stderr, "1st malloc(512): %p\n", a);
fprintf(stderr, "2nd malloc(256): %p\n", b);
strcpy(a, "AAAAAAAA");
strcpy(b, "BBBBBBBB");
fprintf(stderr, "first allocation %p points to %s\n", a, a);
fprintf(stderr, "Freeing the first one...\n");
free(a);
c = malloc(500);
fprintf(stderr, "3rd malloc(500): %p\n", c);
strcpy(c, "CCCCCCCC");
fprintf(stderr, "3rd allocation %p points to %s\n", c, c);
fprintf(stderr, "first allocation %p points to %s\n", a, a);
}

1st malloc(512): 0x8f1010
2nd malloc(256): 0x8f1220
first allocation 0x8f1010 points to AAAAAAAA
Freeing the first one...
3rd malloc(500): 0x8f1010
3rd allocation 0x8f1010 points to CCCCCCCC
first allocation 0x8f1010 points to CCCCCCCC

在分配内存时,malloc 会先 到 unsorted bin(或者fastbins) 中查找适合的被 free 的 chunk,如果没有,就会 把 unsorted bin 中的所有 chunk 分别放入到所属的 bins 中,然后再去这些 bins 里 去找合适的 chunk。可以看到第三次 malloc 的地址和第一次相同,即 malloc 找到了第一次 free 掉的 chunk,并把它重新分配。

分配完内容

pwndbg> heap
Allocated chunk
Addr: 0x602000
Size: 0x00
pwndbg> x/6gx 0x602000
0x602000:	0x0000000000000000	0x0000000000000211
0x602010:	0x4141414141414141	0x0000000000000000
0x602020:	0x0000000000000000	0x0000000000000000
pwndbg> x/6gx 0x602210
0x602210:	0x0000000000000000	0x0000000000000111
0x602220:	0x4242424242424242	0x0000000000000000
0x602230:	0x0000000000000000	0x0000000000000000
pwndbg> x/6gx 0x602320
0x602320:	0x0000000000000000	0x0000000000020ce1
0x602330:	0x0000000000000000	0x0000000000000000
0x602340:	0x0000000000000000	0x0000000000000000

free第一个后:

pwndbg> x/6gx 0x602000
0x602000:	0x0000000000000000	0x0000000000000211
0x602010:	0x00007ffff7dd1d78	0x00007ffff7dd1d78
0x602020:	0x0000000000000000	0x0000000000000000
pwndbg> x/6gx 0x602210
0x602210:	0x0000000000000210	0x0000000000000111
0x602220:	0x4242424242424242	0x0000000000000000
0x602230:	0x0000000000000000	0x0000000000000000
pwndbg> x/6gx 0x602320
0x602320:	0x0000000000000000	0x0000000000020ce1
0x602330:	0x0000000000000000	0x0000000000000000
0x602340:	0x0000000000000000	0x0000000000000000

重新申请内存以后:

pwndbg> x/6gx 0x602000
0x602000:	0x0000000000000000	0x0000000000000211
0x602010:	0x4343434343434343	0x00007ffff7dd1d00
0x602020:	0x0000000000000000	0x0000000000000000

我们可以看到在空闲块(前一会被free的位置)的地方重新被首先分配上内容,即first_fit内存分配算法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值