当前位置: 代码迷 >> QT开发 >> 内存泄漏有关问题
  详细解决方案

内存泄漏有关问题

热度:235   发布时间:2016-04-25 05:06:23.0
内存泄漏问题
#define _CRTDBG_MAP_ALLOC  
#include <iostream>
#include<stdlib.h>  
#include<crtdbg.h>

int main()
{
cout<<"test"<<endl;
{
int* pInt = new int(10);
cout<<*pInt<<endl;
}

_CrtDumpMemoryLeaks();
system("pause");
return 0;
}



如果不使用 #define _CRTDBG_MAP_ALLOC 语句,内存泄漏的输出是这样的:

Detected memory leaks!
Dumping objects ->
{45} normal block at 0x00441BA0, 2 bytes long.
Data: <AB> 41 42 
可是我使用啦#define _CRTDBG_MAP_ALLOC 语句,内存泄漏的输出是一样的 请问是怎么回事呐..


------解决方案--------------------
_CRTDBG_MAP_ALLOC宏对malloc有效, 对new无效
你可以自行添加

C/C++ code
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)#define new DEBUG_NEW
------解决方案--------------------
会提示 在哪个文件的哪一行呀
调试运行看output窗口

C/C++ code
#define _CRTDBG_MAP_ALLOC#include <iostream>#include<stdlib.h>   #include<crtdbg.h>using namespace std;#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)#define new DEBUG_NEWint main(){    cout<<"test"<<endl;    {        int* pInt = new int(10);        cout<<*pInt<<endl;    }    //double* pDouble = (double*)malloc(10);    _CrtDumpMemoryLeaks();    system("pause");    return 0;}
------解决方案--------------------
这里解释了为什么对new无效以及应该怎么做(如同#1楼#3楼所指出)http://support.microsoft.com/kb/140858

<crtdbg.h>里也有描述:
C/C++ code
#if defined(_CRTDBG_MAP_ALLOC) && defined(_CRTDBG_MAP_ALLOC_NEW)/* We keep these inlines for back compatibility only; * the operator new defined in the debug libraries already calls _malloc_dbg, * thus enabling the debug heap allocation functionalities. * * These inlines do not add any information, due that __FILE__ is expanded * to "crtdbg.h", which is not very helpful to the user. *  * The user will need to define _CRTDBG_MAP_ALLOC_NEW in addition to * _CRTDBG_MAP_ALLOC to enable these inlines. */_Ret_bytecap_(_Size) inline void * __CRTDECL operator new(size_t _Size)        { return ::operator new(_Size, _NORMAL_BLOCK, __FILE__, __LINE__); }_Ret_bytecap_(_Size) inline void* __CRTDECL operator new[](size_t _Size)        { return ::operator new[](_Size, _NORMAL_BLOCK, __FILE__, __LINE__); }#endif  /* _CRTDBG_MAP_ALLOC && _CRTDBG_MAP_ALLOC_NEW */
------解决方案--------------------
补充一下

#define _CRTDBG_MAP_ALLOC
#define _CRTDBG_MAP_ALLOC_NEW

为避免重定义,VC编译选项里须开启 /Ob1(内联),同时把/ZI 改成 /Zi,否则与内联冲突

然后就可以发现泄露总被定位到
Detected memory leaks!
Dumping objects ->
×××\Microsoft Visual Studio 9.0\VC\include\crtdbg.h(1203)

这个信息是 not very helpful to the user.

因此不如不定位
------解决方案--------------------
地址丢了不代表内存就被释放了,哥哥.

指针是指针, 内存是内存.
------解决方案--------------------
探讨呐个。。。我的程序是Qt程序
  相关解决方案