C/C++内存泄漏及检测 #include <crtdbg.h>

来源:互联网 发布:苹果好软件推荐 编辑:程序博客网 时间:2024/06/06 00:29

根据关键字“内存检测”,可以搜到很多相关工具。

C/C++内存泄漏及检测

http://www.cnblogs.com/skynet/archive/2011/02/20/1959162.html

该篇帖子,只要在程序中加入一些调试语句,当然仅适合在VC环境中。

经测试,

_CrtDumpMemoryLeaks()

似乎只能定位malloc,而不能定位new。


贴上测试代码(开发环境:Visual Studio 2008):

//工具+选项+文本编辑器+(C++)+常规 ->行号#define _CRTDBG_MAP_ALLOC#include "stdlib.h"#include "crtdbg.h" #include <iostream>using namespace std;int* getInt() {int* p = (int*)malloc(sizeof(int));*p = 100;return p;} char* GetMemory(char *p, int num){    p = (char*)malloc(sizeof(char) * num);return p;} int main(int argc,char** argv){    char *str = NULL;    char *p = GetMemory(str, 100);free(p);    cout<<"Memory leak test!"<<endl;int* pInt = getInt();cout << *pInt << endl;free(pInt);    _CrtDumpMemoryLeaks();    return 0;}


原创粉丝点击