内存泄漏及检测

来源:互联网 发布:金融合作大数据平台 编辑:程序博客网 时间:2024/05/21 19:42

背景

内存泄漏:未能正确释放以前分配的内存的 bug。

内存泄漏会因为减少可用内存的数量从而降低计算机的性能。最终,在最糟糕的情况下,过多的可用内存被分配掉导致全部或部分设备停止正常工作,或者应用程序崩溃。

windows

一般在vs中,我们利用C 运行时 (CRT) 库来检测和识别内存泄漏。

C 运行时库运行原理

内存分配要通过CRT在运行时实现,只要在分配内存和释放内存时分别做好记录,程序结束时对比分配内存和释放内存的记录就可以确定是不是有内存泄漏。

说白了,定位的关键:对应用程序的内存状态拍快照。

示例

#define _CRTDBG_MAP_ALLOC#include <stdlib.h>#include <iostream>#include <crtdbg.h>using namespace std;_CrtMemState s1, s2, s3;void getMemory(char *p,int num){    p = (char*)malloc(sizeof(char)*num);}int _tmain(int argc, _TCHAR* argv[]){    _CrtMemCheckpoint( &s1 );    char *str = NULL;    getMemory(str,100);    _CrtMemCheckpoint( &s2 );    if ( _CrtMemDifference( &s3, &s1, &s2) )        _CrtMemDumpStatistics( &s3 );    cout<< "memory leak test."<<endl;    _CrtDumpMemoryLeaks();    return 0;}

我们也可以利用process hacker管理工具来查看内存泄露。

linux

内存泄露检测工具valgrind。

官网:http://www.valgrind.org

示例

#include <stdio.h>#include <stdlib.h>void getMemory(char *p,int num){    p = (char*)malloc(sizeof(char)*num);}int main(void){    char *str = NULL;    getMemory(str,100);    return 0;}

编译

g++ memory.cpp -o memory

使用内存错误检测器检测。

valgrind --tool=memcheck ./memory

总结

在内存使用完之后,我们需要free(p)并将指针p指向NULL,否则就会出现野指针。

0 0
原创粉丝点击