什么是内存泄漏,如何进行检测内存泄漏

内存泄漏:由于疏忽或者错误造成程序未能释放已经不再使用的情况,内存泄漏并不是指内存在物理上的错误消失,而是程序分配某段内存后,由于设计错误,丢失了对这段内存的控制,因而造成了内存浪费。

如何进行内存泄漏的检测
检测内存泄漏的方法:
1.使用调试器和C运行库(CRT)调试堆函数。
具体函数:_CrtSetDbgFlag()可以在作用于结束位置,自动调用_CrtDumpMemoryLeaks()。如下所示:

    //#define _CRTDBG_MAP_ALLOC  //该定义可以看出哪一行有内存泄漏。
void GetMemory(char**p,int num)
{
         *p = (char *)malloc(num);
}
int main()
{
        char *str = NULL;
        GetMemory(&str, 100);
               strcpy(str, "hello world");
               printf("%s\n", str);
               _CrtDumpMemoryLeaks();
                       system("pause");
                       return 0;

}

这里写图片描述可以看到哪一行出现了内存泄漏

_CrtMemState:表示内存状态数据类型。
 _CrtMemDumpStatistics:输出统计信息。
_CrtMemDifference:比较两个内存状态是否发生了泄漏。
_CrtMemCheckpoint //获取内存状态 
void GetMemory(char**p,int num)
{
         *p = (char *)malloc(num);
}
int main()
{
        char *str = NULL;
        GetMemory(&str, 100);
               strcpy(str, "hello world");
               printf("%s\n", str);
               _CrtDumpMemoryLeaks();
               _CrtMemState s1, s2, s3;
               _CrtMemCheckpoint(&s1);
               int *pi = new int[10];
               //delete[] pi;
               _CrtMemCheckpoint(&s2);
               if (_CrtMemDifference(&s3, &s1, &s2))
               {
                       _CrtMemDumpStatistics(&s3);//输出统计信息
               }
               /*free(str);
                       str = NULL;*/
                       system("pause");
                       return 0;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/xiaodu655/article/details/81153020
今日推荐