Added memory block fragmenting.

This commit is contained in:
Arron David Nelson 2024-02-08 17:24:49 -08:00
parent 14d4e0ee67
commit 0b25fa434f

28
main.c
View File

@ -52,6 +52,21 @@ struct block* find_first(size_t s)
return current; return current;
} }
struct block* fragment_block(struct block* in, size_t s)
{
size_t totalSize = BLOCK_SIZE + s;
struct block* b = (struct block*)((char*)(in + 1) + (in->size - totalSize));
b->size = s;
b->prev = in;
b->next = in->next;
b->free = 0;
in->size -= totalSize;
in->next = b;
return b;
}
/// Will find or allocate a memory block. /// Will find or allocate a memory block.
/// @param [in] size The size of the memory block to request. /// @param [in] size The size of the memory block to request.
/// @returns The requested memory on the heap. /// @returns The requested memory on the heap.
@ -66,13 +81,9 @@ void* malloc(size_t size)
{ {
b = find_first(alignedSize); b = find_first(alignedSize);
if (!b) if (!b)
{
b = extend_heap(alignedSize); b = extend_heap(alignedSize);
} else if (b->size > BLOCK_SIZE + alignedSize)
/* b = fragment_block(b, alignedSize);
else
Fragment here if possible.
*/
} }
else else
{ {
@ -95,6 +106,9 @@ void free(void* ptr)
return; return;
struct block* b = (struct block*)ptr - 1; struct block* b = (struct block*)ptr - 1;
if (b->free)
return;
b->free = 1; b->free = 1;
while (b->prev && b->prev->free) while (b->prev && b->prev->free)
@ -124,5 +138,7 @@ int main()
free(a); free(a);
free(b); free(b);
int* c = (int*)malloc(sizeof(int));
return 0; return 0;
} }