From 94ed0dbd5c7aec3e445dc85dfd7d373ce7ab37d7 Mon Sep 17 00:00:00 2001 From: j2-mcdaid <jack2.mcdaid@live.uwe.ac.uk> Date: Fri, 6 Dec 2024 17:57:20 +0000 Subject: [PATCH] Upload New File --- Worksheets/Worksheet2/Task 3/downBump.hpp | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Worksheets/Worksheet2/Task 3/downBump.hpp diff --git a/Worksheets/Worksheet2/Task 3/downBump.hpp b/Worksheets/Worksheet2/Task 3/downBump.hpp new file mode 100644 index 0000000..98e34be --- /dev/null +++ b/Worksheets/Worksheet2/Task 3/downBump.hpp @@ -0,0 +1,47 @@ + +#ifndef DOWNBUMP_HPP +#define DOWNBUMP_HPP + +#include <cstddef> +#include <iostream> +#include <stdexcept> + +// This allocator starts at the top of the heap and bumps down +class downBump{ +private: + char* current; + char* heap_start; + std::size_t heap_size; + +public: + // constructor + explicit downBump(std::size_t size) : heap_size(size){ + heap_start = new char[size]; + current = heap_start + size; + } + + // destructor + ~downBump(){ + delete[] heap_start; + } + + // template for memory management, checks that there is space for pointer to bump down + template <typename T> + T* alloc(std::size_t count = 1){ + std::size_t total_size = count * sizeof(T); + if(current - total_size < heap_start){ + throw std::bad_alloc(); + } + current -= total_size; + return reinterpret_cast<T*>(calloc); + } + + // reset pointer to top of heap + void reset(){ + current = heap_start + heap_size; + + } +}; + + +#endif \ No newline at end of file -- GitLab