_CrtMemDumpAllObjectsSince()函数不能检测泄漏,如果删除数组调用而不是delete []数组 [英] _CrtMemDumpAllObjectsSince() function is not able to detect leaks if delete array called instead of delete []array

查看:369
本文介绍了_CrtMemDumpAllObjectsSince()函数不能检测泄漏,如果删除数组调用而不是delete []数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些示例代码:

#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;
}

正如你所看到的,我没有使用 delete [] arr ,仍然没有得到任何泄漏。

As you can see that I have not used delete [] arr and still I did not get any leaks.

任何人都可以更正它,并解释为什么 _CrtMemDumpAllObjectsSince()不是在上面的代码中转储泄露。 p>

Can anyone please correct it and explain me why _CrtMemDumpAllObjectsSince() is not dumping leaks in above code.

推荐答案

官方回答是配对 new [] with delete 会给出未定义的行为,因此您不能指望从该点开始的任何有用的信息。

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.

非正式答案通常更多有帮助的是,当你这样做( new [] with delete )通常发生的是内存块被返回到堆,但是,析构函数不会在数组中的对象上被调用。换句话说,这些对象没有被正确地销毁, 被占用的内存被释放。因为它只检查内存块已被释放(并且没有dtors的知识), _CrtMemDumpAllObjectsSince()将不会注意到任何问题。

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;
}

这可能会泄漏内存, delete [] stuff; 而不是 delete stuff; (实际上,做一个快速检查,对我来说,它是平面的崩溃,因为,所以你仍然可能不会得到泄漏报告,但你肯定会知道一些东西出了问题匆忙)。

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).

这篇关于_CrtMemDumpAllObjectsSince()函数不能检测泄漏,如果删除数组调用而不是delete []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆