问题
Here is some sample code:
#include <crtdbg.h>
#include <windows.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
int main()
{
int* arr = new int[10];
delete arr; //not using delete [] arr
_CrtMemDumpAllObjectsSince(NULL); // dumping leak logs
return 0;
}
As you can see that I have not used delete [] arr
and still I did not get any leaks.
Can anyone please correct it and explain me why _CrtMemDumpAllObjectsSince()
is not dumping leaks in above code.
回答1:
The official answer is that pairing new[]
with delete
gives undefined behavior, so you can't count on anything useful happening from that point onward.
The unofficial answer that's generally more helpful is that when you do this (new[]
with delete
) what normally happens is that the memory block gets returned to the heap, but the destructors don't get invoked on the objects in the array. In other words, those objects aren't properly destroyed, but the memory the occupied gets freed. Since it's only checking that blocks of memory have been freed (and has no knowledge of dtors), _CrtMemDumpAllObjectsSince()
won't notice any problem.
On the other hand, consider something like this:
class stupid {
char *junk;
public:
stupid() { junk = new char[10]; }
~stupid() { delete [] junk; }
};
int main() {
stupid *stuff = new stupid[10];
delete stuff;
// delete [] stuff;
_CrtMemDumpAllObjectsSince(NULL);
return 0;
}
This will probably leak memory as-is, but quit leaking it when you use the delete [] stuff;
instead of delete stuff;
(actually, doing a quick check, I find that at least for me it flat-out crashes as-is, so you still may not get a leak report, but you'll definitely know something's wrong in a hurry).
回答2:
Visual c++'s delete operator used on an array is documented as having unpredictable results. I think because youve got an array of ints the memory is being correctly freed because each element int the array has no side effects if not destroyed.
Try doing the same thing with an array of user defined types where each object allocates its own memory for something and frees it in the destructor. I believe you'll have different results.
来源:https://stackoverflow.com/questions/10545436/crtmemdumpallobjectssince-function-is-not-able-to-detect-leaks-if-delete-arra