allocator delete checks

This commit is contained in:
Eduardo Bart 2011-07-13 01:19:12 -03:00
parent 5299ac0233
commit fbaa89d342
2 changed files with 27 additions and 12 deletions

View File

@ -234,8 +234,10 @@ void *Allocator::allocate(size_t bytes)
} else { } else {
disableAllocator(); disableAllocator();
void* p = malloc(bytes + sizeof(void *)); char *allocatedBuffer = (char *)malloc(sizeof(AllocationHead) + bytes);
void* usedPtr = (void *)((char *)p + sizeof(void *)); AllocationHead *head = (AllocationHead *)allocatedBuffer;
void *p = (void *)(allocatedBuffer + sizeof(AllocationHead));
static void *buffer[128]; static void *buffer[128];
int size = backtrace(buffer, 128); int size = backtrace(buffer, 128);
AllocationBlock* block = findBlock(&buffer[1], size - 1, bytes); AllocationBlock* block = findBlock(&buffer[1], size - 1, bytes);
@ -253,11 +255,13 @@ void *Allocator::allocate(size_t bytes)
m_allocationsBlocks.insert(block); m_allocationsBlocks.insert(block);
} }
block->records += 1; block->records++;
*((void **)p) = (void *)block;
head->block = block;
head->magicNumber = MAGIC_NUMBER;
enableAllocator(); enableAllocator();
return usedPtr; return p;
} }
} }
@ -279,13 +283,18 @@ void Allocator::deallocate(void *p)
} else { } else {
disableAllocator(); disableAllocator();
void *allocatedPtr = (void *)((char *)p - sizeof(void *)); p = (void*)((char *)p - sizeof(AllocationHead));
AllocationBlock *block = (AllocationBlock *)(*((void **)allocatedPtr)); AllocationHead *head = (AllocationHead *)p;
block->records--; if(head->magicNumber == MAGIC_NUMBER) {
memset(allocatedPtr, 0, block->bytes + sizeof(void *)); head->block->records--;
free(allocatedPtr); memset(p, 0, head->block->bytes + sizeof(AllocationHead));
free(p);
} else {
printf("invalid delete address\n");
printBacktrace();
}
enableAllocator(); enableAllocator();
} }

View File

@ -10,6 +10,8 @@
#include <boost/thread.hpp> #include <boost/thread.hpp>
#endif #endif
#define MAGIC_NUMBER 0xA1B2C3D4
struct AllocationBlock struct AllocationBlock
{ {
unsigned int bytes; unsigned int bytes;
@ -18,6 +20,12 @@ struct AllocationBlock
unsigned int records; unsigned int records;
}; };
struct AllocationHead
{
unsigned int magicNumber;
AllocationBlock *block;
};
struct block_hash : std::unary_function<AllocationBlock *, std::size_t> { struct block_hash : std::unary_function<AllocationBlock *, std::size_t> {
std::size_t operator()(const AllocationBlock *block) const { std::size_t operator()(const AllocationBlock *block) const {
std::size_t seed = 0; std::size_t seed = 0;
@ -46,8 +54,6 @@ struct block_equal_to : std::binary_function<AllocationBlock *, AllocationBlock
} }
}; };
//TODO: use mem tags
class Allocator class Allocator
{ {
public: public: