我正在研究cs:app malloc lab
(我不是在寻找已实施的答案,只是高级流程),如果您不熟悉,请求malloc()
的实施。
我有大小,状态为in_use
的堆块,以及指向下一个/上一个空闲块的指针(如果没有分配块),这最适合链接列表< / em>的免费块(显式免费列表)。
因为我们已经给出了堆的最大大小为2 ^ 32,我正在考虑将其切换到BST中的隔离列表,其中根节点定义大小类并且具有指向其空闲列表的指针(例如,大小为2 ^ n的对象存储在节点列表中node->class == n
)。
Intuition告诉我使用AVL树可以加快查找空闲块和插入新的大小类,并使用隔离列表有助于减少碎片,但我仍然相对较新的思考这些类型的系统。有人可以确认/否认我的推理吗? (希望这个问题不是太模糊!)
答案 0 :(得分:1)
start with two pointers.
#define SIZE_OF_HEAP = &endHeap - &Heap;
freePtr = &Heap;
Heap = NULL; // at start, the first linked list entry has no following entry
usedPtr = NULL;
with each allocation, insert the address into the usedPtr list
update the freePtr list to 'skip around' the allocated block
with each free, remove the block info from the userPtr list
insert the block info into the freePtr list (by address magnitude)
check if any two freePtr blocks are adjacent
if adjacent, the merge into a single block
The heap processing should have an 'initial' state, for
any initialization
(like setting the initial values of the usedPtr and freePtr
linked list head values
then change state to 'ready')
be sure to handle cases such as when the address passed to free() is not on the usedPtr linked list
be sure to handle cases such as when there is no freePtr block large enough to accommodate the requested block size.
Note: these linked lists, other than the head pointers,
are actually embedded in the heap at the beginning of each block.
Should also keep a small buffer at the end of each allocated block
set it to some known value, like '0xdead' or the address of the block
so can check to see if the heap has been corrupted
effectively this results in two linked lists,
between the two linked lists, all of the heap is covered.
note: the address passed back to the caller
is actually the address past the end of the linked list entry for the block.
SO an actual allocation is slightly larger than what the user requested.
be sure each returned address to the user is on a 32/64 bit boundary.