Compare commits

..

2 Commits

2 changed files with 38 additions and 60 deletions

5
.idea/vcs.xml generated
View File

@ -1,10 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitSharedSettings">
<option name="FORCE_PUSH_PROHIBITED_PATTERNS">
<list />
</option>
</component>
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>

49
main.c
View File

@ -23,12 +23,13 @@ struct block* last = NULL;
/// @returns The new memory block.
struct block* extend_heap(size_t s)
{
// Ensure the allocated size is at least the minimum block size
if (s < MINIMUM_BLOCK_SIZE)
s = MINIMUM_BLOCK_SIZE;
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;
@ -57,10 +58,6 @@ struct block* find_first(size_t s)
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)
{
size_t totalSize = BLOCK_SIZE + s;
@ -84,19 +81,24 @@ void* malloc(size_t size)
{
struct block* b;
size = ALIGN4(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(size);
b = find_first(alignedSize);
if (!b)
b = extend_heap(size);
else if (b->size > BLOCK_SIZE + size)
b = fragment_block(b, size);
b = extend_heap(alignedSize);
else if (b->size > BLOCK_SIZE + alignedSize)
b = fragment_block(b, alignedSize);
}
else
{
b = extend_heap(size);
b = extend_heap(alignedSize);
if (!b)
return NULL;
@ -106,25 +108,6 @@ void* malloc(size_t size)
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.
/// @param [in] ptr The memory to flag as free.