I'm looking for a memory debug strategy in C++. I have written an application using QT. I'm using Windows 7. The used compiler is MinGW. In debug mode, I sometimes got the following debug message: HEAP CORRUPTION DETECTED: after Normal Block (#...) at 0x...
I guess, the following happens: The memory block is freed using delete. After that, the memory is used.
Most of the time, this will work without any problem. But sometimes, this leads to an application crash. My question is, how to debug this error? I'm thinking about replacing the operator new/delete.
Consider the following new/delete operator:
struct MemHandle
{
void* ptr;
size_t size;
}
void * operator new(std::size_t n) throw(std::bad_alloc)
{
MemHandle Mem;
void* p = malloc(n);
Mem.ptr = p;
Mem.size = n;
//TODO: Store Mem
}
void operator delete(void * p) throw()
{
MemHandle Mem = GetMemHandle(p);
memset(p, 0, Mem.size);
free(p);
}
In this case, when the memory is reused after delete, the program will immediately crash. Is this a good strategy, or do you have a better option?