Newer
Older
tree-os / src / kernel / lib / memory / alloc.c
@lukas lukas on 3 Apr 2021 737 bytes improve memory allocator
#include <lib/memory/alloc.h>
#include <stdint.h>
#include <lib/textMode/stdio.h>

MemoryBlock* firstBlock;

void initMemoryAllocation(uint32_t kernelEnd) {
    firstBlock = (MemoryBlock*) kernelEnd;
    firstBlock->next = 0x00;
    firstBlock->last = 0x00;
    firstBlock->state = FREE;
    firstBlock->size = -1;
}

void* malloc(uint32_t size) {
    MemoryBlock* current = firstBlock;
    while (current->next != 0x00) {
        current = current->next;
    }
    MemoryBlock* next = (MemoryBlock*) ((void*) (current + 1) + size);
    next->last = current;
    next->state = FREE;
    next->next = 0x00;
    next->size = -1;
    current->next = next;
    current->size = size;
    current->state = IN_USE;
    return (void*) current;
}