Earlier today I asked this question.
After spending some time investigating this issue, I have discovered what is going on. I am posting this as a new question because I think it is interesting enough to track as a separate issue. I will update that question with the answer (and a link to this one).
Launching unit test from debugger
// Construct object
Object* pObject = new Object(...);
// Pointer value of pObject == 0x05176960
// Lots of other code
// ...
// Destroy object
delete pObject;
// Construct object again
pObject = new Object(...);
// Pointer value of pObject == 0x05560194 /* Different memory location */
Launching unit test from command line
// Construct object
Object* pObject = new Object(...);
// Pointer value of pObject == 0x05176960
// Lots of other code
// ...
// Destroy object
delete pObject;
// Construct object again
pObject = new Object(...);
// Pointer value of pObject == 0x05176960 /* Same memory location */
In summary:
- When launching the unit test from the command line, subsequent calls to
new
to allocate anObject
(delete
ing the previousObject
before allocating a new one) always return the same address in memory. - When launching the unit test from the debugger, subsequent calls to
new
to allocate anObject
(delete
ing the previousObject
before allocating a new one) always return a unique address in memory.
The problem is that because allocations of Object
always get the same address in memory when launching through the command line, a map which I am accessing which has stored the old pointer can still be used and the test won't crash. But I want my unit test to crash when the defect fix is not in place, to ensure that it doesn't silently fail and the defect doesn't come back.
There are 2 parts to my question:
Why would the heap manager re-use the same part of memory when launching a unit test from the command line, but not when I launch the unit test from the debugger?
Is there a compiler setting I could use on my test harness, or a method I can call to prevent the heap manager from re-using a section of memory that I have deleted, to allow me to correctly write my unit test? 1
1Obviously one way of doing this is to not delete the original object, but the part of the code that allocates this is in my production code, and I doing this would result in memory leaks.