Given the following constraints:
- No multithreading.
- No care about hardware cache utilization.
Wondering what a reasonably optimal memory allocation scheme would look like.
From my limited knowledge, one implementation is Free Lists, but it says they have some issues. Then there is buddy management and dynamic allocation.
Overall, the procedure seems to be like:
- Allocate block
- Find available free space
- If some exists, then use it.
- Otherwise
- Calculate the changes you would have to make to the memory blocks to satisfy the request. This results in a set of movements of blocks to open up an appropriately sized gap to fulfill the request.
- Given you know how to shuffle the blocks around, do that.
- Then allocate the memory.
- Potentially shift around some other blocks if you have time, to get rid of some of the fragmentation.
- Return
The middle part of that is where it starts to get difficult. There must be some data structure associated with the free/used blocks perhaps, to make it efficient to navigate around in them. Then wondering how much time can we spend looking for an ideal location. It's like you have to calculate and predict what the best case scenario is, but that would require computing a lot of stuff. Then there's the issue of doing sort of GC, and clean up the memory organization. All of this on top of balancing copying memory which is a small performance hit. Who would've thought it is so complex.
To summarize, wondering what a standard memory allocation procedure looks like that is pretty optimal. I have seen the C implementations of malloc variations but it is hard to gather all of the pieces from how large and complex it is.
For reference, I am thinking along the lines of how if a memory was organized like this:
type 1
type 2
type 3
If they are packed together then if type 1
needs more space, wondering does it append to the end:
[empty]
type 2
type 3
type 1
Or if it would give more space by shifting:
type 1
[empty]
type 2
type 3
But then it starts to get complicated. You might mitigate this a little bit by preallocating slightly more space than necessary, but eventually it will outgrow its location, so then how to balance it out. That's where I get confused. I'm coming from JavaScript land.
malloc
tag seems to hint at C, but in C, for example, we cannot rearrange blocks as there is insufficient information to repair the program after doing so; thus, an algorithm for C would necessarily omit such actions.malloc
'ed, so to C's runtime,malloc
ed blocks are just blocks of memory that can be (used and)free
ed. C also uses pointers, of course. So onemalloc
ed block may have pointer(s) within it referring to othermalloc
ed block(s). If you move a latter such block, you would have to make a corresponding update to any pointers to it. But since C doesn't trackmalloc
block types, we cannot find these pointers that require corresponding updates. And that is the tip of the iceberg for C and block moving/compaction.