gbowne1implfix #1

Merged
Karutoh merged 10 commits from gbowne1implfix into main 2024-02-08 17:41:13 -08:00
Showing only changes of commit 8b520b4bed - Show all commits

70
main.c
View File

@ -4,6 +4,7 @@
#define ALIGN4(s) (((((s)-1)>>2)<<2)+4) #define ALIGN4(s) (((((s)-1)>>2)<<2)+4)
#define BLOCK_SIZE sizeof(struct block) #define BLOCK_SIZE sizeof(struct block)
#define MINIMUM_BLOCK_SIZE 16
/// The memory block's header. /// The memory block's header.
struct block struct block
@ -22,22 +23,27 @@ struct block* last = NULL;
/// @returns The new memory block. /// @returns The new memory block.
struct block* extend_heap(size_t s) struct block* extend_heap(size_t s)
{ {
struct block* b = sbrk(0); struct block* b = sbrk(0);
if (sbrk(BLOCK_SIZE + s) == (void*)-1) // Ensure the allocated size is at least the minimum block size
return NULL; if (s < MINIMUM_BLOCK_SIZE) {
s = MINIMUM_BLOCK_SIZE;
}
b->size = s; if (sbrk(BLOCK_SIZE + s) == (void*)-1)
b->prev = last; return NULL;
b->next = NULL;
b->free = 0;
if (last) b->size = s;
last->next = b; b->prev = last;
b->next = NULL;
b->free = 0;
last = b; if (last)
last->next = b;
return b; last = b;
return b;
} }
/// Finds the first block that will fit the given size. /// Finds the first block that will fit the given size.
@ -73,30 +79,36 @@ struct block* fragment_block(struct block* in, size_t s)
/// @todo Fragmenting functionality. /// @todo Fragmenting functionality.
void* malloc(size_t size) void* malloc(size_t size)
{ {
struct block* b; struct block* b;
size_t alignedSize = ALIGN4(size); size_t alignedSize = ALIGN4(size);
if (first) // Enforce the minimum block size
{ if (alignedSize < MINIMUM_BLOCK_SIZE) {
b = find_first(alignedSize); alignedSize = MINIMUM_BLOCK_SIZE;
if (!b) }
b = extend_heap(alignedSize);
else if (b->size > BLOCK_SIZE + alignedSize)
b = fragment_block(b, alignedSize);
}
else
{
b = extend_heap(alignedSize);
if (!b)
return NULL;
first = b; if (first)
} {
b = find_first(alignedSize);
if (!b)
b = extend_heap(alignedSize);
else if (b->size > BLOCK_SIZE + alignedSize)
b = fragment_block(b, alignedSize);
}
else
{
b = extend_heap(alignedSize);
if (!b)
return NULL;
return b + 1; first = b;
}
return b + 1;
} }
/// Will flag the provided memory as free and will defragment other blocks adjacent to it. /// Will flag the provided memory as free and will defragment other blocks adjacent to it.
/// @param [in] ptr The memory to flag as free. /// @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. /// @note If all data after the provided memory is free, it will reduce the heap size.