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内存分配算法。