I decided to not use heap in my program and create a custom memory manager to retrieve memory chunks from a big global array of uint8_t(u8). I chose u8 since 8 bits is a byte. The very big MEMORY_BLOCK_SIZE is not a problem since in Release builds the compiler will remove the unused bytes. I keep track of free memory chunks with something i call "lookups".
#include <assert.h>
// NOTE: null is a redefinition of NULL
// NOTE: u8 = uint8_t
// NOTE: u64 = uint64_t
#define MEMORY_BLOCK_SIZE 8388608
#define MEMORY_LOOKUPS 8
static u8 memoryBlock[ MEMORY_BLOCK_SIZE ];
static u8* memoryLookups[ MEMORY_LOOKUPS ];
static u64 memoryLookupsSizes[ MEMORY_LOOKUPS ];
void memoryInit( void )
{
memoryLookups[ 0 ] = memoryBlock;
memoryLookupsSizes[ 0 ] = MEMORY_BLOCK_SIZE;
}
u8* requestMemoryChunk( u64 size )
{
assert( size );
u8* usablePtr = null;
u64 ptrPosition;
for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )
{
if( ( !( memoryLookups[ i ] ) ) &&
( memoryLookupsSizes[ i ] >= size ) )
{
usablePtr = memoryLookups[ i ];
ptrPosition = i;
break;
}
}
assert( usablePtr );
u8* block = usablePtr;
memoryLookupsSizes[ ptrPosition ] -= size;
if( !( memoryLookupsSizes[ ptrPosition ] ) )
memoryLookups[ ptrPosition ] = null;
else
memoryLookups[ ptrPosition ] = usablePtr + size;
return block;
}
void freeMemoryChunk( u64 size, u8* block )
{
assert( block && size );
for( u64 i = 0; i < MEMORY_LOOKUPS; ++i )
{
if( ! ( memoryLookups[ i ] ) )
{
memoryLookups[ i ] = block;
memoryLookupsSizes[ i ] = size;
break;
}
}
}
```
requestfunction, shouldn't it beif(lookups && sizes)rather thanif(!lookups && sizes)\$\endgroup\$for( u64 i = MEMORY_LOOKUPS; i >= 0; --i )will never stop,iwill wrap around to the maximum value of uint64_t. \$\endgroup\$