Hi. As some of you may know I am attempting to get various debugging tools turned into headers for inclusion of a project. This time around I started making a smartptr that could:
1. Allocate a new object of type T
2. If that object is used to access memory outside of the ptr buffer it could throw an assertion.
By way of example if:
Code:
// old way
int numElements = 5;
double *ptrDoubleArray = new double[numElements];
// accessed like
ptrDoubleArray[4] = 5; // okay
ptrDoubleArray[10] = 5; // is not OK
// With smartptr
SmartPtr ptrSmart = new double[numElements];
ptrSmart[4] = 5; //still OK
ptrSmart[20] = 5; //smart ptr knows it "owns" addresses ptrSmart to ptrSmart + 5
// so with an overloaded [] operator, it will internally do
if( newRequestedElement > ptr + 5)
{
assert();
}
else
{
return ptr[newRequestedElement];
}
So that logic (roughly) will tell me if an attempt to access the ptr is outside of its range plus the usual stuff a smart ptr does. However what I want to do now is detect when:
1. The pointer itself is damaged.
2. The data underneath the pointer has been stepped on
3. The pointer itself has been damaged.
I have theories on how to do this but would like to know either if
A. I am nuts for trying this...wait scratch that.
B. There is something like this out there.
My theory is to use basic memory protection techniques:
When the smart pointer does the basic allocation, it allocates memory sizeof(class T) plus two blocks at the beginning and end of that block 2*sizeof(classT) and here is the trick: when I allocate the memory with the guard buffers as described above, I cope the value of the actual ptr into both ends of the memory window. Further when the class is used normally a hash of the original memory block. The at periodic times in the source you can call checkPtr(someSmartPtr) which will compare the guards at the front and end of the memory block with the value of the actual ptr. If one of the guards and the ptr match but not the other one, it will assert with a stacktrace saying "Beginning" (if that is the odd-man out) or "End" if the latter guard doesn't match "Has been overwritten in file XXX.cpp on line YYY".
If that is OK, the actual memory window is rehashed and if the hash value doesn't match the previous check, it reports that memory has been stepped on. No idea how to tell who did it yet but this is a start. If the value of the ptr and the beginning and ending guards match AND the checksum is correct it will return a success value.
Not as good as a memory tool but could be useful.
So does something like this exist?
TIA
Jeff