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

View File

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