3 ms·
Can you share the algorithm?
by ciconia 6y ago
Can you share the algorithm?
- munificent 6y agoSearch for "small block allocator" and you'll probably find some good resources.
- JoeAltmaier 6y agoI just look in a hash table by rounded block size. If there's something there, its a linked list of 'free' blocks; unlink one and return a pointer to the data portion. If there's nothing there then malloc the rounded size plus my header, fill out my header (linked list fields plus block nominal size plus signature) and return a pointer to the data portion. On a free/delete, look backwards from the given pointer for a signature. If its not there, just free it with the library. If its there, look in the hash table by the nominal size and link this block there. That's it! You can protect the hash table and linked lists with a critical section if you want to be multi-threaded. Optional features include a table of block counts for diagnostic purposes. Maybe an assert on the number of blocks, to catch runaway allocation. All that is a page or two of code.