Last active
June 14, 2017 08:16
-
-
Save tamaskenez/9563001737597928c9c933a5ebf80a9f to your computer and use it in GitHub Desktop.
concept for an memory allocator which works like a stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StackAllocator { | |
public: | |
StackAllocator(int capacity) | |
: storage(new char[capacity]) | |
, free_storage(storage) | |
, storage_end(storage + capacity) | |
{} | |
~StackAllocator() { delete[] storage; } | |
void* malloc(size_t s) { | |
assert(free_storage + s <= storage_end); | |
blocks.push_back(free_storage) | |
auto result = free_storage; | |
free_storage += s; | |
return result; | |
} | |
void free(void *p) { | |
assert(!blocks.empty()); | |
if (blocks.back() == p) { | |
// shortcut for freeing the last block | |
blocks.pop_back(); | |
free_storage = p; | |
} else { | |
// bin-search for p | |
auto it = std::lower_bound(blocks.begin(), blocks.end(), p); | |
assert(it != blocks.end() && *it == p); | |
*it |= 1; //mark free | |
} | |
// maintenance: remove freed blocks from top | |
while(!blocks.empty() && (blocks.back() & 1)) { | |
free_storage = blocks.back() & ~(intptr_t)1 | |
blocks.pop_back(); | |
} | |
} | |
private: | |
char* storage; | |
char* free_storage; // storage <= free_storage <= storage_end | |
char* storage_end; | |
vector<char*> blocks; //odd pointer means freed block | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment