gbowne1 version of implementation with more implementations done #4

Merged
Karutoh merged 4 commits from gbowne1_impl into main 2024-02-14 18:08:17 -08:00
Showing only changes of commit fe9d9e3836 - Show all commits

21
main.c
View File

@ -68,7 +68,7 @@ struct block *find_first(size_t s)
struct block *fragment_block(struct block *in, size_t s) struct block *fragment_block(struct block *in, size_t s)
{ {
// Calculate the size of the new block, including the block header // Calculate the size of the new block, including the block header
size_t newBlockSize = ALIGN16(s) + BLOCK_SIZE; size_t newBlockSize = s + BLOCK_SIZE;
// Check if the current block can be split // Check if the current block can be split
if (in->size <= newBlockSize) if (in->size <= newBlockSize)
@ -108,7 +108,8 @@ struct block *find_best_fit(size_t s)
{ {
if (current->free && current->size >= s) if (current->free && current->size >= s)
{ {
if (!best_fit || current->size < best_fit->size) if (best_fit && current->size < best_fit->size) // Check for NULL before comparison
{
{ {
best_fit = current; best_fit = current;
} }
@ -116,6 +117,7 @@ struct block *find_best_fit(size_t s)
current = current->next; current = current->next;
} }
return best_fit; return best_fit;
}
} }
/// Will find or allocate a memory block. /// Will find or allocate a memory block.
@ -221,11 +223,22 @@ void my_custom_free(void *ptr)
b->prev->next = b->next; b->prev->next = b->next;
b = b->prev; b = b->prev;
} }
while (b->next && b->next->free)
// If there is a next block and it's free, merge with it
if (b->next && b->next->free)
{ {
// Merge with next block
b->size += BLOCK_SIZE + b->next->size; b->size += BLOCK_SIZE + b->next->size;
b->next = b->next->next; b->next = b->next->next;
if (b->next)
{
b->next->prev = b;
}
}
// After merging, update the 'last' pointer if necessary
if (!b->next)
{
last = b;
} }
// Check if we can shrink the heap // Check if we can shrink the heap