Added ralloc function.
This commit is contained in:
parent
0b25fa434f
commit
c0da3fdefe
36
main.c
36
main.c
@ -52,6 +52,10 @@ struct block* find_first(size_t s)
|
|||||||
return current;
|
return current;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fragments an existing free memory block into the given size.
|
||||||
|
/// @param [in] in The memory block to fragment.
|
||||||
|
/// @param [in] s The size of the new memory block.
|
||||||
|
/// @returns The new memory block.
|
||||||
struct block* fragment_block(struct block* in, size_t s)
|
struct block* fragment_block(struct block* in, size_t s)
|
||||||
{
|
{
|
||||||
size_t totalSize = BLOCK_SIZE + s;
|
size_t totalSize = BLOCK_SIZE + s;
|
||||||
@ -75,19 +79,19 @@ void* malloc(size_t size)
|
|||||||
{
|
{
|
||||||
struct block* b;
|
struct block* b;
|
||||||
|
|
||||||
size_t alignedSize = ALIGN4(size);
|
size = ALIGN4(size);
|
||||||
|
|
||||||
if (first)
|
if (first)
|
||||||
{
|
{
|
||||||
b = find_first(alignedSize);
|
b = find_first(size);
|
||||||
if (!b)
|
if (!b)
|
||||||
b = extend_heap(alignedSize);
|
b = extend_heap(size);
|
||||||
else if (b->size > BLOCK_SIZE + alignedSize)
|
else if (b->size > BLOCK_SIZE + size)
|
||||||
b = fragment_block(b, alignedSize);
|
b = fragment_block(b, size);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
b = extend_heap(alignedSize);
|
b = extend_heap(size);
|
||||||
if (!b)
|
if (!b)
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
@ -97,6 +101,26 @@ void* malloc(size_t size)
|
|||||||
return b + 1;
|
return b + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void* realloc(void* ptr, size_t new_size)
|
||||||
|
{
|
||||||
|
if (!ptr)
|
||||||
|
return malloc(new_size);
|
||||||
|
|
||||||
|
if (!new_size)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
struct block* b = (struct block*)ptr - 1;
|
||||||
|
if (b->free)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
if (b->size == new_size)
|
||||||
|
return ptr;
|
||||||
|
else if (b->size > BLOCK_SIZE + new_size)
|
||||||
|
return fragment_block(b, new_size) + 1;
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
/// 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.
|
||||||
|
Loading…
Reference in New Issue
Block a user