Skip to content
Snippets Groups Projects
Commit 61b725fc authored by j2-pelczar's avatar j2-pelczar :cowboy:
Browse files

Upload New File

parent 09499ab7
No related branches found
No related tags found
No related merge requests found
#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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment