diff --git a/worksheet_two/task_1_bump_allocator/bump_allocator.hpp b/worksheet_two/task_1_bump_allocator/bump_allocator.hpp new file mode 100644 index 0000000000000000000000000000000000000000..db46123de4971fa0797c84c29fb156886e893a37 --- /dev/null +++ b/worksheet_two/task_1_bump_allocator/bump_allocator.hpp @@ -0,0 +1,59 @@ +#ifndef BUMP_ALLOCATOR_HPP +#define BUMP_ALLOCATOR_HPP + +#include <cstddef> // For std::size_t +#include <iostream> + +class BumpAllocator { +private: + char* memory; // Start of the memory chunk + char* next; // Current bump pointer + std::size_t capacity; // Total capacity of the allocator + std::size_t used; // Number of allocations made + +public: + // Constructor: initializes the heap with a given size + explicit BumpAllocator(std::size_t size) + : memory(new char[size]), next(memory), capacity(size), used(0) {} + + // Destructor: frees the allocated memory + ~BumpAllocator() { + delete[] memory; + } + + // Allocate memory for N objects of type T + template <typename T> + T* alloc(std::size_t count = 1) { + std::size_t requiredBytes = count * sizeof(T); + if (next + requiredBytes > memory + capacity) { + std::cerr << "Out of memory: cannot allocate " << requiredBytes << " bytes.\n"; + return nullptr; + } + T* allocation = reinterpret_cast<T*>(next); + next += requiredBytes; + ++used; + return allocation; + } + + // Deallocate memory (only works when all allocations are freed) + void dealloc() { + if (used > 0) { + --used; + if (used == 0) { + next = memory; // Reset the bump pointer + } + } else { + std::cerr << "Error: No allocations to deallocate.\n"; + } + } + + // Display allocator status + void printStatus() const { + std::cout << "Allocator status:\n"; + std::cout << " Capacity: " << capacity << " bytes\n"; + std::cout << " Used: " << (next - memory) << " bytes\n"; + std::cout << " Allocations: " << used << "\n"; + } +}; + +#endif