p = (char*)malloc(sizeof(char) * num);//使用new也能够检测出来
08
}
09
10
intmain(intargc,char** argv)
11
{
12
char*str = NULL;
13
GetMemory(str, 100);
14
cout<<"Memory leak test!"<<endl;
15
//如果main中存在while循环调用GetMemory
16
//那么问题将变得很严重
17
//while(1){GetMemory(...);}
18
return0;
19
}
实际中不可能这么简单,如果这么简单也用不着别的方法,程序员一眼就可以看出问题,此程序只用于测试。
2、Windows平台下的内存泄漏检测
2.1、检测是否存在内存泄漏问题
Windows平台下面Visual Studio 调试器和 C 运行时 (CRT) 库为我们提供了检测和识别内存泄漏的有效方法,原理大致如下:内存分配要通过CRT在运行时实现,只要在分配内存和释放内存时分别做好记录,程序结束时对比分配内存和释放内存的记录就可以确定是不是有内存泄漏。在vs中启用内存检测的方法如下:
==6118== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==6118== at 0x4024F20: malloc (vg_replace_malloc.c:236) ==6118== by 0x8048724: GetMemory(char*, int) (in /home/netsky/workspace/a.out) ==6118== by 0x804874E: main (in /home/netsky/workspace/a.out)
Things to notice: • There is a lot of information in each error message; read it carefully. • The 6118 is the process ID; it’s usually unimportant. • The first line ("Heap Summary") tells you what kind of error it is. • Below the first line is a stack trace telling you where the problem occurred. Stack traces can get quite large, and be confusing, especially if you are using the C++ STL. Reading them from the bottom up can help.
• The code addresses (eg. 0x4024F20) are usually unimportant, but occasionally crucial for tracking down weirder bugs.
The stack trace tells you where the leaked memory was allocated. Memcheck cannot tell you why the memory leaked, unfortunately. (Ignore the "vg_replace_malloc.c", that’s an implementation detail.) There are several kinds of leaks; the two most important categories are: • "definitely lost": your program is leaking memory -- fix it! • "probably lost": your program is leaking memory, unless you’re doing funny things with pointers (such as moving them to point to the middle of a heap block)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人