You can't really implement a memory manager system like this in standard C. It would have to rely on standard extensions and specific compiler options. The main reason for this is "the strict aliasing rule"... (What is the strict aliasing rule?)
...but also alignment, you shouldn't write a library that hands out misaligned chunks of memory. If you look at malloc & friends they only work since they have a requirement (from the C standard 7.22.3):
Thepointer returned if the allocation succeeds is suitably aligned so that it may be assigned toa pointer to any type of object with a fundamental alignment requirement and then usedto access such an object or an array of such objects in the space allocated (until the spaceis explicitly deallocated).
As noted in another review, you shouldn't come up with home-brewed, secret aliases for standardized terms. Use
stdint.h
withuint8_t
etc. UseNULL
. In particular, don't re-defineNULL
to something custom since that can cause all manner of subtle bugs. See What's the difference between null pointers and NULL? for details.Bug here:
for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )
Anu64
is always >= 0. Decent compilers ought to warn you here. In general, bugs like this can be avoided by always iterating from 0 and upwards, then change the indexing instead:arr[MAX - i]
etc.Generally, library quality code does not check if parameters passed are NULL, 0 etc. Such things are handled by documentation and making it the caller's responsibility to not pass on trash parameters.
Your routines ought to keep track of the last used memory location instead of searching for it in run-time. I take it that some of these might be freed so you'd get gaps in the look-up table, but then you should ask yourself if an array is really the right container class to use. You could for example use a BST instead, sorted after memory address.
Your code doesn't seem to address fragmentation at all.
The very big MEMORY_BLOCK_SIZE is not a problem since in Release builds the compiler will remove the unused bytes.
I wouldn't be so sure about that, it depends a lot on system and context.
↧
Answer by Lundin for Fixed memory manager in C
↧