diff --git a/Worksheet2/bumpalld.hpp b/Worksheet2/bumpalld.hpp new file mode 100644 index 0000000000000000000000000000000000000000..220f9801f9374bff2942b190c0eca28b44879f63 --- /dev/null +++ b/Worksheet2/bumpalld.hpp @@ -0,0 +1,40 @@ +#include <iostream> +#include <cstddef> + +class BumpAllocator { + char* start; // Pointer to the start of the allocated memory block + char* current; // Pointer to the current position in the memory block (end side) + size_t size; // Total size of the memory block + +public: + // Constructor for the BumpAllocator + BumpAllocator(size_t size) : size(size) { + start = new char[size]; // Allocate a memory block of the given size + current = start + size; // Initialize the current pointer to the end of the block + } + + // Function to allocate memory within the block, moving downwards + void* allocate(size_t allocSize) { + // Check if there is enough space left in the block for the requested size + if (current - allocSize < start) { + //std::cout << "Not enough space in the block for allocation!" << std::endl; + return nullptr; // Return nullptr if there is not enough space + } + current -= allocSize; // "Bump" the current pointer backward by the requested size + //std::cout << "Memory allocated successfully!" << std::endl; + return current; // Return the new current position (start of allocated block) + } + + // Function to reset the allocator + void reset() { + current = start + size; // Reset the current pointer back to the end of the block + //std::cout << "Allocator reset!" << std::endl; + } + + // Destructor for the BumpAllocator + ~BumpAllocator() { + delete[] start; // Deallocate the memory block when the allocator is destroyed + //std::cout << "Memory block deallocated!" << std::endl; + } +}; +