Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Source: C++ Game Development Primer - Chapter 1
- #include <iostream>
- using namespace std;
- class DummyClass{
- double a,b;
- public:
- DummyClass(){cout<<"Const\n";}
- virtual ~DummyClass(){cout<<"Dest\n";}
- void* operator new(size_t size)
- {
- cout << "Allocating "<<size<<" byte for a new object\n";
- //DummyClass* o = ::new DummyClass;
- void* o = malloc(size);
- return o;
- }
- void operator delete(void *mem)
- {
- cout << "Freeing ...\n";
- //::delete DummyClass;
- free(mem);
- }
- };
- struct MemoryAllocationHeader{
- void* start;
- void* nextFree;
- size_t size;
- };
- namespace MyMemoryManager
- {
- char mem[1024*1024];
- }
- void* operator new(size_t size)
- {
- MemoryAllocationHeader* newHeader = reinterpret_cast<MemoryAllocationHeader*>(MyMemoryManager::mem);
- // First empty slot when nextFree=0x00
- while(newHeader->nextFree!= nullptr)
- {
- newHeader = reinterpret_cast<MemoryAllocationHeader*>(newHeader->nextFree);
- }
- newHeader->size = size;
- newHeader->start = newHeader+sizeof(MemoryAllocationHeader);
- newHeader->nextFree = (char*)(newHeader->start) + size;
- return newHeader->start;
- }
- void operator delete(void* memory)
- {
- MemoryAllocationHeader* current = reinterpret_cast<MemoryAllocationHeader*>(MyMemoryManager::mem);
- MemoryAllocationHeader *last = nullptr;
- while(current->start!=memory)
- {
- last = current;
- current = reinterpret_cast<MemoryAllocationHeader*>(current->nextFree);
- }
- if(last!=nullptr)
- last->nextFree = current->nextFree;
- current->size = 0;
- current->start = nullptr;
- }
- void PrintAllocations() {
- MemoryAllocationHeader* pHeader = reinterpret_cast<MemoryAllocationHeader*>(MyMemoryManager::mem);
- while (pHeader != nullptr) {
- std::cout << pHeader << std::endl;
- std::cout << pHeader->start << std::endl;
- std::cout << "NextHeader: "<<pHeader->nextFree << std::endl; std::cout << pHeader->size << std::endl;
- pHeader = reinterpret_cast<MemoryAllocationHeader*> (pHeader->nextFree);
- std::cout << std::endl << std::endl;
- }
- }
- int main()
- {
- auto x1 = new DummyClass;
- auto x2 = new int;
- auto x3 = new DummyClass;
- PrintAllocations();
- cout<<"---------------------\n";
- delete x2;
- PrintAllocations();
- cout<<"---------------------\n";
- x2 = new int;
- PrintAllocations();
- cout<<"---------------------\n";
- delete x1;
- delete x2;
- delete x3;
- PrintAllocations();
- cout<<"---------------------\n";
- x2 = new int;
- PrintAllocations();
- cout<<"---------------------\n";
- delete x2;
- PrintAllocations();
- cout<<"---------------------\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement