Building Your Own Allocator

While it is certainly possible to use the low-level mmap and munmap functions to create and delete areas of virtual memory, C programmers typically find it more convenient and more portable to use a dynamic memory allocator when they need to acquire additional virtual memory at run time. The C standard library provides an explicit allocator known as the malloc package. But we want to build our own allocator here.

      Our allocator itself is contained in a source file that users can compile and link into their applications. The allocator exports three functions to application programs:

extern int mm_init(void);
extern void *mm_malloc(size_t size);
extern void mm_free(void *ptr);
      The mm_init function initializes the allocator, returning 0 if successful and -1 otherwise. The mm_malloc and mm_ free functions have the same interfaces and semantics as their system counterparts malloc and free.

      Before calling mm_malloc or mm_ free, the application must initialize the heap by calling mm_init function. The mm_init function gets four words from the memory system and initializes them to create the empty free list. It then extends the heap by CHUNKSIZE bytes and creates the initial free block. At this point, the allocator is initialized and ready to accept allocate and free requests from the application.

      An application frees a previously allocated block by calling the mm_ free function, which frees the requested block, and then merges adjacent free blocks using the boundary-tags coalescing technique. The free list format we have chosen—with its prologue and epilogue blocks that are always marked as allocated — allows us to ignore the potentially troublesome edge conditions where the requested block is at the beginning or end of the heap. Without these special blocks, the code would be messier, more error-prone, and slower because we would have to check for these rare edge conditions on each and every free request.

      An application requests a block of size bytes of memory by calling the mm_malloc function. The allocator must adjust the requested block size to allow room for the header and the footer, and to satisfy the double-word alignment requirement. For requests over eight bytes, the general rule is to add in the overhead bytes and then round up to the nearest multiple of eight. Once the allocator has adjusted the requested size, it searches the free list for a suitable free block. If there is a fit, then the allocator places the requested block and optionally splits the excess, and then returns the address of the newly allocated block. If the allocator cannot find a fit, then it extends the heap with a new free block, places the requested block in the new free block and optionally splitting the block, and then return a pointer to the newly allocated block.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章