Added memory block fragmenting.
This commit is contained in:
parent
14d4e0ee67
commit
0b25fa434f
28
main.c
28
main.c
@ -52,6 +52,21 @@ struct block* find_first(size_t s)
|
||||
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.
|
||||
/// @param [in] size The size of the memory block to request.
|
||||
/// @returns The requested memory on the heap.
|
||||
@ -66,13 +81,9 @@ void* malloc(size_t size)
|
||||
{
|
||||
b = find_first(alignedSize);
|
||||
if (!b)
|
||||
{
|
||||
b = extend_heap(alignedSize);
|
||||
}
|
||||
/*
|
||||
else
|
||||
Fragment here if possible.
|
||||
*/
|
||||
else if (b->size > BLOCK_SIZE + alignedSize)
|
||||
b = fragment_block(b, alignedSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -95,6 +106,9 @@ void free(void* ptr)
|
||||
return;
|
||||
|
||||
struct block* b = (struct block*)ptr - 1;
|
||||
if (b->free)
|
||||
return;
|
||||
|
||||
b->free = 1;
|
||||
|
||||
while (b->prev && b->prev->free)
|
||||
@ -124,5 +138,7 @@ int main()
|
||||
free(a);
|
||||
free(b);
|
||||
|
||||
int* c = (int*)malloc(sizeof(int));
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user