updated malloc and extended heap

This commit is contained in:
Gregory Kenneth Bowne 2024-02-08 17:34:20 -08:00
parent 0b25fa434f
commit 8b520b4bed

12
main.c
View File

@ -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
@ -24,6 +25,11 @@ struct block* extend_heap(size_t s)
{
struct block* b = sbrk(0);
// Ensure the allocated size is at least the minimum block size
if (s < MINIMUM_BLOCK_SIZE) {
s = MINIMUM_BLOCK_SIZE;
}
if (sbrk(BLOCK_SIZE + s) == (void*)-1)
return NULL;
@ -77,6 +83,11 @@ void* malloc(size_t size)
size_t alignedSize = ALIGN4(size);
// Enforce the minimum block size
if (alignedSize < MINIMUM_BLOCK_SIZE) {
alignedSize = MINIMUM_BLOCK_SIZE;
}
if (first)
{
b = find_first(alignedSize);
@ -97,6 +108,7 @@ void* malloc(size_t size)
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.