struct blk {
size_t size; // long unsigned int 8
struct blk *prev; // 8
struct blk *next; // 8
};
struct blk *first = NULL;
struct blk *last = NULL;
blk 结构体示意:
这里 blk 表示分配的内存的结构体,blk->size 大小包含 blk 结构体本身的大小及分配的内存的大小,地址连续,起始位置为 blk 指针指向的位置。
// void malloc(size_t size)
// ...
if (curr == NULL) {
void *new = sbrk((intptr_t) required_size);
if (new == (void *) -1) { return NULL; }
struct blk *new_blk = (struct blk *) new;
new_blk->size = required_size;
return (void *) (new_blk + 1);
}
// ...
// ...
if (blk_ptr > last) {
//什么要将结构体 blk 指针转换为 char * 指针?
if (((char *) last) + last->size == (char *) blk_ptr) { // @todo 判断 last 与 blk_ptr 是否连续
last->size += blk_ptr->size;
} else {
blk_ptr->next = NULL;
blk_ptr->prev = last;
last->next = blk_ptr;
last = blk_ptr;
}
return;
}
// ..
last 指针转换为 char * 指针后,对其进行算术运算操作,这里是 ((char *) last) + last->size
, 使指针前进指定的字节数,然后比对其指针位置是否与 blk_ptr
相同,相同则表示两块 blk 结构体表示的内存块连续,则将 blk_ptr 插入双向链表的末尾,成为 last.