c++内存泄漏处理(积累)

22 篇文章 0 订阅

写c++程序时,经常会出现内存泄漏的问题,这里从网上找了一种很麻烦的方法:如果想找到每个cpp文件的内存泄漏,都必须在每个cpp加上如下代码:

#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new(_CLIENT_BLOCK, __FILE__, __LINE__)
#define new DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif

下面给出一段测试的代码

test.h

#include <memory.h>

void funNew();
test.cpp

#include "text.h"

#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new(_CLIENT_BLOCK, __FILE__, __LINE__)
#define new DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif

void funNew()
{
	int *p = new int();
}
main.cpp

#include <iostream>
#include <assert.h>
#include "text.h"

#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new(_CLIENT_BLOCK, __FILE__, __LINE__)
#define new DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif

int main()
{
	_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	int* p = new int();
	funNew();
	//delete p;
	return 0;
}

输出

Detected memory leaks!
Dumping objects ->
f:\project1\test.cpp(13) : {157} client block at 0x001E9180, subtype 0, 4 bytes long.
 Data: <    > 00 00 00 00 
f:\project1\main.cpp(17) : {156} client block at 0x001E9140, subtype 0, 4 bytes long.
 Data: <    > 00 00 00 00 
Object dump complete.






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值