Skip to content

Instantly share code, notes, and snippets.

@tamaskenez
Last active June 14, 2017 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamaskenez/9563001737597928c9c933a5ebf80a9f to your computer and use it in GitHub Desktop.
Save tamaskenez/9563001737597928c9c933a5ebf80a9f to your computer and use it in GitHub Desktop.
concept for an memory allocator which works like a stack
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