Fixed forward defragmenting, added reverse defragmenting, and added a line break on second printf.
This commit is contained in:
parent
3b38eddf5d
commit
14d4e0ee67
15
main.c
15
main.c
@ -9,6 +9,7 @@
|
|||||||
struct block
|
struct block
|
||||||
{
|
{
|
||||||
size_t size;
|
size_t size;
|
||||||
|
struct block* prev;
|
||||||
struct block* next;
|
struct block* next;
|
||||||
int free;
|
int free;
|
||||||
};
|
};
|
||||||
@ -27,6 +28,7 @@ struct block* extend_heap(size_t s)
|
|||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
b->size = s;
|
b->size = s;
|
||||||
|
b->prev = last;
|
||||||
b->next = NULL;
|
b->next = NULL;
|
||||||
b->free = 0;
|
b->free = 0;
|
||||||
|
|
||||||
@ -87,7 +89,6 @@ void* malloc(size_t size)
|
|||||||
/// 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.
|
||||||
/// @todo Reverse defragmenting.
|
|
||||||
void free(void* ptr)
|
void free(void* ptr)
|
||||||
{
|
{
|
||||||
if (!ptr)
|
if (!ptr)
|
||||||
@ -96,15 +97,15 @@ void free(void* ptr)
|
|||||||
struct block* b = (struct block*)ptr - 1;
|
struct block* b = (struct block*)ptr - 1;
|
||||||
b->free = 1;
|
b->free = 1;
|
||||||
|
|
||||||
struct block* link = b->next;
|
while (b->prev && b->prev->free)
|
||||||
|
b = b->prev;
|
||||||
|
|
||||||
while (b->next && b->next->free)
|
while (b->next && b->next->free)
|
||||||
{
|
{
|
||||||
b->size += BLOCK_SIZE + b->next->size;
|
b->size += BLOCK_SIZE + b->next->size;
|
||||||
b->next = link->next;
|
b->next = b->next->next;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reverse defragment here.
|
|
||||||
|
|
||||||
if (!b->next)
|
if (!b->next)
|
||||||
brk(b);
|
brk(b);
|
||||||
}
|
}
|
||||||
@ -118,10 +119,10 @@ int main()
|
|||||||
*b = 12;
|
*b = 12;
|
||||||
|
|
||||||
printf("Test 1: %i\n", *a);
|
printf("Test 1: %i\n", *a);
|
||||||
printf("Test 2: %i", *b);
|
printf("Test 2: %i\n", *b);
|
||||||
|
|
||||||
free(b);
|
|
||||||
free(a);
|
free(a);
|
||||||
|
free(b);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user