Is there any benefit to use multiple heaps for memory management purposes?

前端 未结 5 2072
-上瘾入骨i
-上瘾入骨i 2021-02-15 17:37

I am a student of a system software faculty. Now I\'m developing a memory manager for Windows. Here\'s my simple implementation of malloc() and free():

5条回答
  •  长情又很酷
    2021-02-15 18:05

    You have some good thoughts and this'd work for C but in C++ you have destructors, it is VERY important they run.

    You can think of all types as having constructors/destructors, just that logically "do nothing".

    This is about allocators. See "The buddy algorithm" which uses powers of two to align and re-use stuff.

    If I allocate 4 bytes somewhere, my allocator might allocate a 4kb section just for 4 byte allocations. That way I can fit 1024 4 byte things in the block, if I need more add another block and so forth.

    Ask it for 4kb and it wont allocate that in the 4byte block, it might have a separate one for larger requests.

    This means you can keep big things together. If I go 17 bytes then 13 bytes the 1 byte and the 13byte gets freed, I can only stick something in there of <=13 bytes.

    Hence the buddy system and powers of 2, easy to do using lshifts, if I want a 2.5kb block, I allocate it as the smallest power of 2 that'll fit (4kb in this case) that way I can use the slot afterwards for <=4kb items.

    This is not for garbage collection, this is just keeping things more compact and neat, using your own allocator can stop calls to the OS (depending on the default implementation of new and delete they might already do this for your compiler) and make new/delete very quick.

    Heap-compacting is very different, you need a list of every pointer that points to your heap, or some way to traverse the entire memory graph (like spits Java) so when you move stuff round and "compact" it you can update everything that pointed to that thing to where it currently is.

提交回复
热议问题