Compare commits

..

2 Commits

Author SHA1 Message Date
6e9c27b71e Fixed runtime errors. 2024-03-02 12:55:54 -08:00
7464c85692 Fixed a lot of errors and expanded functionality. 2024-03-02 06:42:02 -08:00
5 changed files with 493 additions and 301 deletions

View File

@ -38,9 +38,9 @@ endif ()
set(CMAKE_C_STANDARD 11)
add_executable(CustomHeapManager main.c)
add_executable(CustomHeapManager
src/CHM.c include/CHM.h
src/main.c
)
if (IS_OS_LINUX)
target_link_options(CustomHeapManager PUBLIC)
elseif (IS_OS_WINDOWS)
endif ()
target_include_directories(CustomHeapManager PUBLIC ${PROJECT_SOURCE_DIR}/include)

37
include/CHM.h Normal file
View File

@ -0,0 +1,37 @@
#pragma once
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/syscall.h>
enum MemMode : unsigned char
{
MEM_MODE_SPEED, // Memory will be allocated more quickly but loses memory efficiency.
MEM_MODE_EFFICIENCY, // Memory will be allocated more slowly but gains memory efficiency.
MEM_MODE_BALANCED // Memory will be allocated as quickly as possible but also for the sake of memory efficiency.
};
void set_memory_mode(enum MemMode new_mode);
enum MemMode get_memory_mode();
/// Will find or allocate a memory block appropriately.
/// @param [in] size The size of the memory block to request.
/// @returns The allocated memory address on the heap.
void *malloc(size_t size);
void *realloc(void *ptr, size_t newSize);
/// Will flag the provided memory as free and will defragment other blocks adjacent to it.
/// @param [in] ptr The memory to flag as free.
void free(void *ptr);
size_t get_header_size();
/// Will retrieve the current real byte size of the heap.
/// @returns The size in bytes.
size_t get_heap_size();
void cleanup_memory();

296
main.c
View File

@ -1,296 +0,0 @@
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define ALIGN16(s) (((s) + 15) & ~0x0F)
#define BLOCK_SIZE sizeof(struct block)
#define MINIMUM_BLOCK_SIZE (sizeof(struct block) + 16)
/// The memory block's header.
struct block
{
size_t size;
struct block *prev;
struct block *next;
int free;
};
struct block *first = NULL;
struct block *last = NULL;
/// Extends heap memory upwards, towards zero.
/// @param [in] s The size of the memory needed aligned by 4 bytes.
/// @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 = (struct block *)sbrk(0); // Get the current break
// Attempt to extend the break by s bytes
void *new_break = sbrk(BLOCK_SIZE + s);
if (new_break == (void *)-1)
{
// Handle the error, e.g., by setting an error code or printing an error message
fprintf(stderr, "Failed to extend heap by %zu bytes.\n", s);
return NULL;
}
b->size = s;
b->prev = last;
b->next = NULL;
b->free = 0;
if (last)
last->next = b;
last = 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 *current = first;
while (current && (!current->free || current->size < s))
current = current->next;
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)
{
// Calculate the size of the new block, including the block header
size_t newBlockSize = s + BLOCK_SIZE;
// Check if the current block can be split
if (in->size <= newBlockSize)
{
// Cannot split, return the original block
return in;
}
// Calculate the size of the remainder block
size_t remainderSize = in->size - newBlockSize;
// Create the new block in the remainder space
struct block *newBlock = (struct block *)((char *)(in + 1) + s);
newBlock->size = remainderSize; // Subtract the size of the block header
newBlock->prev = in;
newBlock->next = in->next;
newBlock->free = 1; // Set the new block as free
// Update the current block to reflect the reduced size
in->size = newBlockSize; // Subtract the size of the block header
in->next = newBlock;
// Insert the new block into the linked list of blocks
if (newBlock->next)
{
newBlock->next->prev = newBlock;
}
return newBlock;
}
struct block *find_best_fit(size_t s)
{
struct block *current = first;
struct block *best_fit = NULL;
while (current)
{
if (current->free && current->size >= s)
{
if (best_fit == NULL || current->size < best_fit->size)
{
best_fit = current;
}
}
current = current->next;
}
return best_fit; // This return statement is now outside the while loop
}
/// 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)
{
if (size == 0)
{
return NULL;
}
size = ALIGN16(size); // First align the requested size
size_t total_size = size + BLOCK_SIZE; // Then add the size of the block header
struct block *b;
if (first)
{
b = find_best_fit(size);
if (!b)
{
b = extend_heap(total_size);
if (!b)
{
return NULL; // Check if heap extension failed
}
}
else if (b->size > total_size + MINIMUM_BLOCK_SIZE)
{
b = fragment_block(b, size);
}
}
else
{
b = extend_heap(total_size);
if (!b)
{
return NULL;
}
first = b;
}
b->free = 0; // Mark the block as used
return (char *)b + BLOCK_SIZE; // Return a pointer to the usable memory
}
void *realloc(void *ptr, size_t new_size)
{
if (!ptr)
{
return malloc(new_size);
}
if (new_size == 0)
{
free(ptr);
return NULL;
}
struct block *b = (struct block *)((char *)ptr - BLOCK_SIZE);
if (b->size >= new_size + BLOCK_SIZE)
{
return ptr; // The block is already big enough
}
void *new_ptr = malloc(new_size);
if (!new_ptr)
{
return NULL; // Allocation failed
}
memcpy(new_ptr, ptr, b->size - BLOCK_SIZE); // Copy old data to new block, excluding the header size
free(ptr); // Free the old block
return new_ptr;
}
/// 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.
void free(void *ptr)
{
if (!ptr)
{
return;
}
struct block *b = (struct block *)((char *)ptr - BLOCK_SIZE);
if (b->free)
{
fprintf(stderr, "Double free detected at block %p.\n", ptr);
abort(); // Terminate the program immediately due to serious error
}
b->free = 1;
// Coalesce free blocks
while (b->prev && b->prev->free)
{
// Merge with previous block
b->prev->size += BLOCK_SIZE + b->size;
b->prev->next = b->next;
b = b->prev;
}
// If there is a next block and it's free, merge with it
if (b->next && b->next->free)
{
b->size += BLOCK_SIZE + b->next->size;
b->next = b->next->next;
if (b->next)
{
b->next->prev = b; // Update the prev pointer of the next block
}
}
// After merging, update the 'last' pointer if necessary
if (!b->next)
{
last = b;
}
// Check if we can shrink the heap
if (b == last)
{
// Update 'last' to the previous block or NULL if there's no previous block
last = b->prev;
if (last)
{
last->next = NULL;
}
else
{
first = NULL;
}
// Reduce the program break to release the memory
sbrk(0 - (b->size + BLOCK_SIZE));
}
}
size_t get_heap_size()
{
size_t total_size = 0;
struct block *current = first;
while (current != NULL)
{
total_size += current->size;
current = current->next;
}
return total_size;
}
int main()
{
int *a = (int *)malloc(sizeof(int));
int *b = (int *)malloc(sizeof(int));
int *c = (int *)malloc(sizeof(int)); // Allocate memory for c
*a = 5;
*b = 12;
printf("Test 1: %i\n", *a);
printf("Test 2: %i\n", *b);
printf("Heap Size: %zu Bytes\n", get_heap_size()); // Assuming get_heap_size is implemented
free(a); // Free memory for a
free(b); // Free memory for b
free(c); // Free memory for c
return 0;
}

426
src/CHM.c Normal file
View File

@ -0,0 +1,426 @@
#include "CHM.h"
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/syscall.h>
#define ALIGN4(s) (((((s)-1)>>2)<<2)+4)
#define ALIGN16(s) (((s) + 15) & ~0x0F)
#define ALIGNMENT 4
#define BLOCK_SIZE sizeof(struct Block)
/// The memory block's header.
struct Block
{
size_t size;
struct Block *prev;
struct Block *next;
int free;
};
enum MemMode mode = MEM_MODE_BALANCED;
struct Block *first = NULL;
struct Block *last = NULL;
/// Sets the memory mode for the custom heap manager.
/// @param [in] new_mode The new mode to use.
void set_memory_mode(const enum MemMode new_mode)
{
if (new_mode > MEM_MODE_BALANCED)
{
fprintf(stderr, "The given memory mode, \"%i\", is invalid.", new_mode);
return;
}
mode = new_mode;
}
/// Gets the current memory mode for the custom heap manager.
/// @returns The current mode.
enum MemMode get_memory_mode()
{
return mode;
}
/// Extends heap memory upwards, towards zero.
/// @param [in] s The size of the memory needed aligned by 4 bytes.
/// @returns The new memory block.
struct Block *extend_heap(const size_t s)
{
struct Block* b = (struct Block *)syscall(SYS_brk, NULL);
if ((void *)syscall(SYS_brk, (char *)(b + 1) + s) == (void *)-1)
return NULL;
b->size = s;
b->prev = last;
b->next = NULL;
b->free = 0;
if (last)
last->next = b;
last = b;
return b;
}
/// Will defragment adjacent memory blocks of the given memory block.
/// @param [in] in The memory block to defragment for.
void defragment_adjacent_blocks(struct Block *in)
{
// Go in reverse order to find free memory blocks.
while (in->prev && in->prev->free)
in = in->prev;
// Go in forward order to find memory blocks and merge them.
while (in->next && in->next->free)
{
in->size += BLOCK_SIZE + in->next->size;
in->next = in->next->next;
}
}
/// 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.
void fragment_block(struct Block *in, size_t s)
{
// Create the new block in the remainder space
struct Block *newBlock = (struct Block *)((char *)(in + 1) + s);
newBlock->size = in->size - BLOCK_SIZE - s;
newBlock->prev = in;
newBlock->next = in->next;
newBlock->free = 1;
// Update the current block to reflect the reduced size
in->size = s;
in->next = newBlock;
in->free = 0;
}
struct Block *extend_block(struct Block *in, const size_t newSize)
{
if (!in->next)
{
void *addr = (struct Block *)syscall(SYS_brk, NULL);
if ((void *)syscall(SYS_brk, (char *)addr + (newSize - in->size)) == (void *)-1)
return NULL;
in->size = newSize;
return in;
}
size_t totalSize = in->size;
struct Block *start = in->prev;
struct Block *end = in->next;
while (start && start->free && totalSize < newSize)
{
totalSize += BLOCK_SIZE + start->size;
if (totalSize >= newSize)
break;
start = in->prev;
}
while (end && end->free && totalSize < newSize)
{
totalSize += BLOCK_SIZE + end->size;
if (totalSize >= newSize)
break;
end = end->next;
}
if (totalSize < newSize || (mode == MEM_MODE_EFFICIENCY && totalSize > newSize))
return NULL;
if (!start)
start = in;
if (!end)
end = in;
struct Block *b = start->next;
while (b)
{
start->size += BLOCK_SIZE + b->size;
if (b == end)
break;
b = b->next;
}
start->next = end->next;
start->free = 0;
start->next->prev = start;
if (!start->next)
last = start;
const size_t remainder = start->size - (BLOCK_SIZE + newSize);
if (remainder && !(remainder % ALIGNMENT))
fragment_block(start, newSize);
return start;
}
/// Finds the first block that will fit the given size.
/// @param [in] s The memory aligned size to look for.
/// @returns The matching available memory block.
struct Block *find_first(const size_t s)
{
const size_t totalSize = BLOCK_SIZE + s;
struct Block *current = first;
while (current)
{
if (!current->free || current->size < s)
{
current = current->next;
continue;
}
if (current->size >= s)
break;
current = current->next;
}
return current;
}
/// Finds the first memory block with more ore equal to the given size and fragments it if necessary.
/// @param [in] s The memory aligned size to look for.
/// @returns The matching available memory block.
struct Block *find_balanced(const size_t s)
{
const size_t totalSize = BLOCK_SIZE + s;
struct Block *current = first;
while (current)
{
if (!current->free || current->size < s)
{
current = current->next;
continue;
}
if (current->size == s)
break;
const size_t remainder = current->size - totalSize;
if (remainder && !(remainder % ALIGNMENT))
{
fragment_block(current, s);
break;
}
current = current->next;
}
return current;
}
/// Finds the best fitting memory block with the given size and fragments it if necessary.
/// @param [in] s The memory aligned size to look for.
/// @returns The matching available memory block.
struct Block *find_best_fit(const size_t s)
{
const size_t totalSize = BLOCK_SIZE + s;
unsigned char fragment = 0;
struct Block *best = NULL;
struct Block *current = first;
while (current)
{
if (!current->free || current->size < s)
{
current = current->next;
continue;
}
if (current->size == s)
{
fragment = 0;
best = current;
break;
}
const size_t remainder = current->size - totalSize;
if (best)
{
if (current->size < best->size && remainder && !(remainder % ALIGNMENT))
{
fragment = 1;
best = current;
}
}
else
{
if (remainder && !(remainder % ALIGNMENT))
{
fragment = 1;
best = current;
}
}
current = current->next;
}
if (best && fragment)
fragment_block(best, s);
return best;
}
void *malloc(size_t size)
{
if (!size)
return NULL;
size = ALIGN16(size);
struct Block *b;
if (first)
{
switch (mode)
{
case MEM_MODE_SPEED:
b = find_first(size);
break;
case MEM_MODE_EFFICIENCY:
b = find_best_fit(size);
break;
case MEM_MODE_BALANCED:
b = find_balanced(size);
break;
}
if (!b)
{
b = extend_heap(size);
if (!b)
return NULL;
}
}
else
{
b = extend_heap(size);
if (!b)
return NULL;
first = b;
last = b;
}
return b + 1;
}
void *realloc(void *ptr, size_t newSize)
{
if (!newSize)
return NULL;
if (!ptr)
return malloc(newSize);
newSize = ALIGN16(newSize);
struct Block *b = (struct Block *)ptr - 1;
if (b->free)
return NULL;
if (b->size == newSize)
return b + 1;
const size_t totalSize = BLOCK_SIZE + newSize;
const size_t remainder = b->size - totalSize;
if (b->size < newSize) // Expand memory block if possible.
{
if (!extend_block(b, newSize))
return NULL;
return b + 1;
}
else if (b->size > newSize && remainder && !(remainder % ALIGNMENT)) // Shrink memory block if possible.
{
fragment_block(b, newSize);
return b + 1;
}
return NULL;
}
void free(void *ptr)
{
if (!ptr)
return;
struct Block *b = (struct Block *)ptr - 1;
if (b->free)
{
fprintf(stderr, "Double free detected for the address %p.\n", ptr);
return;
}
b->free = 1;
if (mode != MEM_MODE_SPEED)
defragment_adjacent_blocks(b);
if (!b->next)
{
if (!b->prev)
{
first = NULL;
last = NULL;
}
else
last = b;
syscall(SYS_brk, b);
}
}
size_t get_header_size()
{
return BLOCK_SIZE;
}
size_t get_heap_size()
{
if (!first || !last)
return 0;
return (char*)last + last->size - (char*)first;
}
void cleanup_memory()
{
if (!first || !last)
return;
const struct Block *l = last;
struct Block *current = first;
while (current)
{
if (!current->free)
fprintf(stderr, "Memory at the address %p has not been marked free. Possible memory leak?\n", current + 1);
if (current == l)
break;
current = current->next;
}
syscall(SYS_brk, first);
first = NULL;
last = NULL;
}

25
src/main.c Normal file
View File

@ -0,0 +1,25 @@
#include "CHM.h"
#include <unistd.h>
int main()
{
set_memory_mode(MEM_MODE_BALANCED);
int *a = (int *)malloc(sizeof(int));
*a = 1;
int *b = (int *)malloc(sizeof(int));
*b = 2;
int *c = (int *)malloc(sizeof(int));
*c = 3;
printf("Heap Size: %zu Bytes\n", get_heap_size());
free(a);
free(b);
free(c);
cleanup_memory();
return 0;
}