updated malloc and extended heap
This commit is contained in:
parent
0b25fa434f
commit
8b520b4bed
70
main.c
70
main.c
@ -4,6 +4,7 @@
|
||||
|
||||
#define ALIGN4(s) (((((s)-1)>>2)<<2)+4)
|
||||
#define BLOCK_SIZE sizeof(struct block)
|
||||
#define MINIMUM_BLOCK_SIZE 16
|
||||
|
||||
/// The memory block's header.
|
||||
struct block
|
||||
@ -22,22 +23,27 @@ struct block* last = NULL;
|
||||
/// @returns The new memory block.
|
||||
struct block* extend_heap(size_t s)
|
||||
{
|
||||
struct block* b = sbrk(0);
|
||||
struct block* b = sbrk(0);
|
||||
|
||||
if (sbrk(BLOCK_SIZE + s) == (void*)-1)
|
||||
return NULL;
|
||||
// Ensure the allocated size is at least the minimum block size
|
||||
if (s < MINIMUM_BLOCK_SIZE) {
|
||||
s = MINIMUM_BLOCK_SIZE;
|
||||
}
|
||||
|
||||
b->size = s;
|
||||
b->prev = last;
|
||||
b->next = NULL;
|
||||
b->free = 0;
|
||||
if (sbrk(BLOCK_SIZE + s) == (void*)-1)
|
||||
return NULL;
|
||||
|
||||
if (last)
|
||||
last->next = b;
|
||||
b->size = s;
|
||||
b->prev = last;
|
||||
b->next = NULL;
|
||||
b->free = 0;
|
||||
|
||||
last = b;
|
||||
if (last)
|
||||
last->next = b;
|
||||
|
||||
return b;
|
||||
last = b;
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
/// Finds the first block that will fit the given size.
|
||||
@ -73,30 +79,36 @@ struct block* fragment_block(struct block* in, size_t s)
|
||||
/// @todo Fragmenting functionality.
|
||||
void* malloc(size_t size)
|
||||
{
|
||||
struct block* b;
|
||||
struct block* b;
|
||||
|
||||
size_t alignedSize = ALIGN4(size);
|
||||
size_t alignedSize = ALIGN4(size);
|
||||
|
||||
if (first)
|
||||
{
|
||||
b = find_first(alignedSize);
|
||||
if (!b)
|
||||
b = extend_heap(alignedSize);
|
||||
else if (b->size > BLOCK_SIZE + alignedSize)
|
||||
b = fragment_block(b, alignedSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
b = extend_heap(alignedSize);
|
||||
if (!b)
|
||||
return NULL;
|
||||
// Enforce the minimum block size
|
||||
if (alignedSize < MINIMUM_BLOCK_SIZE) {
|
||||
alignedSize = MINIMUM_BLOCK_SIZE;
|
||||
}
|
||||
|
||||
first = b;
|
||||
}
|
||||
if (first)
|
||||
{
|
||||
b = find_first(alignedSize);
|
||||
if (!b)
|
||||
b = extend_heap(alignedSize);
|
||||
else if (b->size > BLOCK_SIZE + alignedSize)
|
||||
b = fragment_block(b, alignedSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
b = extend_heap(alignedSize);
|
||||
if (!b)
|
||||
return NULL;
|
||||
|
||||
return b + 1;
|
||||
first = b;
|
||||
}
|
||||
|
||||
return b + 1;
|
||||
}
|
||||
|
||||
|
||||
/// Will flag the provided memory as free and will defragment other blocks adjacent to it.
|
||||
/// @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.
|
||||
|
Loading…
Reference in New Issue
Block a user