VS2015内存泄漏检测、追踪

本文介绍了如何在VS2015中检测和追踪内存泄漏问题。通过利用C运行时(CRT)库和Visual Studio调试器,结合特定的设置,可以在内存泄漏发生时中断程序并查看调用堆栈,精确定位泄漏源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前写了一篇VS2010内存泄漏检测和追踪的方法,最近在2015上发现不太适用(监听找不到msvcr140d.dll),现介绍一个适用2015的方法。

内存泄漏定义

内存泄漏指的是在程序里动态申请的内存在使用完后,没有进行释放,导致这部分内存没有被系统回收,久而久之,可能导致程序内存不断增大,系统内存不足

内存泄漏危害

  • 系统可用内存越来越小
  • 机器卡顿
  • 系统崩溃
  • 排查起来很困难

定位方法

内存泄漏方法有很多种,也可以借助第三方插件 Visual Leak Detector(开源,免费)进行排查,本篇文章介绍一种 借助Visual Studio 调试器和 C 运行时 (CRT) 库进行排查的方法。

1、我们以一个小demo进行分析:

#include "stdafx.h"
#include <string>
 
using namespace std;
class CStudent
{
public:
    CStudent(int age, std::string name) : m_age(age), m_name(name) {}
    ~CStudent() {}
 
    int Age(){return m_age;}
private:
    int m_age;
    std::string m_name;
};
 
void MemoryTest()
{
    CStudent* pStudent = new CStudent(20, "xiaoming");
    int age = pStudent->Age();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    MemoryTest();
    return 0;
}

很容易可以发现在MemoryTest函数内第一行是有内存泄漏的,但此时编译器以及程序运行时不会报任何内存泄漏信息。

2、加入相关代码

#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
 
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#include "stdafx.h"
#include <string>
 
 
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
 
class CStudent
{
public:
    CStudent(int age, std::string name) : m_age(age), m_name(name) {}
    ~CStudent() {}
 
    int Age(){return m_age;}
private:
    int m_age;
    std::string m_name;
};
 
void MemoryTest()
{
    CStudent* pStudent = new CStudent(20, "xiaoming");
    int age = pStudent->Age();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
    MemoryTest();
    return 0;
}

此时输出信息会报内存泄漏

3、重新运行程序,在监听中加入{,,msvcr100d.dll}_crtBreakAlloc,值为225,程序会在内存泄漏的代码位置中断

int _tmain(int argc, _TCHAR* argv[])
{
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetBreakAlloc(225);
	MemoryTest();
	return 0;
}

4、点击中断,查看调用堆栈,即可看到内存泄漏代码位置

5、在相应位置释放资源即可
 

VS2010内存泄漏检测、追踪方法:

https://blog.csdn.net/lihaidong1991/article/details/103486118

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值