diff --git a/main.c b/main.c index b15c67f..8951147 100644 --- a/main.c +++ b/main.c @@ -5,6 +5,7 @@ #define ALIGN4(s) (((((s)-1)>>2)<<2)+4) #define BLOCK_SIZE sizeof(struct block) +/// The memory's block header. struct block { size_t size; @@ -14,6 +15,10 @@ struct block struct block* freeList = NULL; +/// Extends heap memory upwards, towards zero. +/// @param [in] last The last block that the newly created block will link to. +/// @param [in] s The size of the memory needed aligned by 4 bytes. +/// @returns The new memory block. struct block* extend_heap(struct block* last, size_t s) { struct block* b = sbrk(0); @@ -31,6 +36,9 @@ struct block* extend_heap(struct block* last, size_t s) return b; } +/// Finds the first block that will fit the given size. +/// @param [in] s The 4 byte aligned size to look for. +/// @returns The matching available memory block. struct block* find_first(size_t s) { struct block* current = freeList; @@ -40,6 +48,8 @@ struct block* find_first(size_t s) return current; } +/// Finds the last memory block in the linked list to attach a new block to. +/// @returns The last memory block. struct block* find_last() { struct block* current = freeList; @@ -49,6 +59,10 @@ struct block* find_last() return current; } +/// Will find or allocate a memory block. +/// @param [in] size The size of the memory block to request. +/// @returns The requested memory on the heap. +/// @todo Fragmenting functionality. void* malloc(size_t size) { struct block* b; @@ -60,6 +74,10 @@ void* malloc(size_t size) b = find_first(alignedSize); if (!b) b = extend_heap(find_last(), alignedSize); + /* + else + Fragment here if possible. + */ } else { @@ -73,6 +91,10 @@ void* malloc(size_t size) return (char*)b + BLOCK_SIZE; } +/// Will flag the provided memory as free and will defragment other blocks adjacent to it. +/// @param [in] ptr The memory to flag as free. +/// @note If all data after the provided memory is free, it will reduce the heap size. +/// @todo Reverse defragmenting. void free(void* ptr) { if (!ptr) @@ -88,6 +110,8 @@ void free(void* ptr) b->next = link->next; } + // Reverse defragment here. + if (!b->next) brk(b); }