Optimized code by adding last block global variable.

This commit is contained in:
Arron David Nelson 2024-02-08 16:44:26 -08:00
parent 6525d5f2b9
commit 3b38eddf5d

31
main.c
View File

@ -13,13 +13,13 @@ struct block
int free;
};
struct block* freeList = NULL;
struct block* first = NULL;
struct block* last = 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* extend_heap(size_t s)
{
struct block* b = sbrk(0);
@ -33,6 +33,8 @@ struct block* extend_heap(struct block* last, size_t s)
if (last)
last->next = b;
last = b;
return b;
}
@ -41,24 +43,13 @@ struct block* extend_heap(struct block* last, size_t s)
/// @returns The matching available memory block.
struct block* find_first(size_t s)
{
struct block* current = freeList;
struct block* current = first;
while (current && (!current->free || current->size < s))
current = current->next;
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;
while (current && current->next)
current = freeList->next;
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.
@ -69,11 +60,13 @@ void* malloc(size_t size)
size_t alignedSize = ALIGN4(size);
if (freeList)
if (first)
{
b = find_first(alignedSize);
if (!b)
b = extend_heap(find_last(), alignedSize);
{
b = extend_heap(alignedSize);
}
/*
else
Fragment here if possible.
@ -81,11 +74,11 @@ void* malloc(size_t size)
}
else
{
b = extend_heap(NULL, alignedSize);
b = extend_heap(alignedSize);
if (!b)
return NULL;
freeList = b;
first = b;
}
return b + 1;