User:A22347/Memory Manager
From OSDev Wiki
Here is the memory manager for my kernel. Feel free to use.
#define BLOCK_SIZE 64 #define MEMORY_BASE 0x18000000 #define MEMORY_HIGH 0x80000000 #define MEMORY (MEMORY_HIGH - MEMORY_BASE) #define BLOCKS (MEMORY / BLOCK_SIZE) char blocksUsed[BLOCKS] = { 0 }; int tried = 0; uint8_t* lastFreeAddress = MEMORY_BASE; uint8_t* lastMallocAddress = MEMORY_BASE; void* malloc (size_t size) { tried = 0; int stage = 0; uint8_t* ptr = lastFreeAddress; unsigned int blocksAlloced = 0; while (blocksAlloced < size) { if (blocksUsed[(((unsigned int) ptr + blocksAlloced) - MEMORY_BASE) / BLOCK_SIZE] == 0) { blocksAlloced += BLOCK_SIZE ; } else { ptr += blocksAlloced + BLOCK_SIZE ; if (stage == 0) { stage = 1; ptr = lastMallocAddress; } blocksAlloced = 0; } } for (int i = 0; i < blocksAlloced / BLOCK_SIZE ; ++i) { if (i == blocksAlloced / BLOCK_SIZE - 1) { blocksUsed[((((unsigned int) ptr) - MEMORY_BASE) / BLOCK_SIZE) + i] = 2; //show that this is the last in the block } else { blocksUsed[((((unsigned int) ptr) - MEMORY_BASE) / BLOCK_SIZE) + i] = 1; } } lastMallocAddress = ptr + blocksAlloced; freeBytesApprox -= blocksAlloced; return ptr; } void free (void *blk) { unsigned int locator = blk; while (blocksUsed[((locator - MEMORY_BASE) / BLOCK_SIZE)]) { if (blocksUsed[((locator - MEMORY_BASE) / BLOCK_SIZE)] == 2) { blocksUsed[((locator - MEMORY_BASE) / BLOCK_SIZE)] = 0; break; } blocksUsed[((locator - MEMORY_BASE) / BLOCK_SIZE)] = 0; locator += BLOCK_SIZE; } lastFreeAddress = blk; freeBytesApprox += locator - (int) blk + BLOCK_SIZE; }