Added documentation.

This commit is contained in:
Arron David Nelson 2024-02-08 02:00:57 -08:00
parent 1517046258
commit a9fcd9102f

24
main.c
View File

@ -5,6 +5,7 @@
#define ALIGN4(s) (((((s)-1)>>2)<<2)+4) #define ALIGN4(s) (((((s)-1)>>2)<<2)+4)
#define BLOCK_SIZE sizeof(struct block) #define BLOCK_SIZE sizeof(struct block)
/// The memory's block header.
struct block struct block
{ {
size_t size; size_t size;
@ -14,6 +15,10 @@ struct block
struct block* freeList = NULL; struct block* freeList = NULL;
/// Extends heap memory upwards, towards zero.
/// @param [in] last The last block that the newly created block will link to.
/// @param [in] s The size of the memory needed aligned by 4 bytes.
/// @returns The new memory block.
struct block* extend_heap(struct block* last, size_t s) struct block* extend_heap(struct block* last, size_t s)
{ {
struct block* b = sbrk(0); struct block* b = sbrk(0);
@ -31,6 +36,9 @@ struct block* extend_heap(struct block* last, size_t s)
return b; return b;
} }
/// Finds the first block that will fit the given size.
/// @param [in] s The 4 byte aligned size to look for.
/// @returns The matching available memory block.
struct block* find_first(size_t s) struct block* find_first(size_t s)
{ {
struct block* current = freeList; struct block* current = freeList;
@ -40,6 +48,8 @@ struct block* find_first(size_t s)
return current; return current;
} }
/// Finds the last memory block in the linked list to attach a new block to.
/// @returns The last memory block.
struct block* find_last() struct block* find_last()
{ {
struct block* current = freeList; struct block* current = freeList;
@ -49,6 +59,10 @@ struct block* find_last()
return current; return current;
} }
/// 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.
/// @todo Fragmenting functionality.
void* malloc(size_t size) void* malloc(size_t size)
{ {
struct block* b; struct block* b;
@ -60,6 +74,10 @@ void* malloc(size_t size)
b = find_first(alignedSize); b = find_first(alignedSize);
if (!b) if (!b)
b = extend_heap(find_last(), alignedSize); b = extend_heap(find_last(), alignedSize);
/*
else
Fragment here if possible.
*/
} }
else else
{ {
@ -73,6 +91,10 @@ void* malloc(size_t size)
return (char*)b + BLOCK_SIZE; return (char*)b + BLOCK_SIZE;
} }
/// 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.
/// @todo Reverse defragmenting.
void free(void* ptr) void free(void* ptr)
{ {
if (!ptr) if (!ptr)
@ -88,6 +110,8 @@ void free(void* ptr)
b->next = link->next; b->next = link->next;
} }
// Reverse defragment here.
if (!b->next) if (!b->next)
brk(b); brk(b);
} }