当前位置: 首页 > 工具软件 > LeakTracer > 使用案例 >

LeakTracer-内存泄露检测工具

邵沛
2023-12-01

LeakTracer-Linux、Solaris和HP-UX下跟踪和分析C++程序中的内存泄漏。

推荐到LeakTracer的github上去看看,连接是https://github.com/fredericgermain/LeakTracer


1.有3种方法可以加载libleaktracer

  (1)Link your program with libleaktracer.a,加载静态库

  (2)Link your program with libleaktracer.so,加载动态库

  (3)use the LD_PRELOAD environment variable to be sure it is loaded before any other library


2.可以直接利用LeakTracer API启动、停止检测,也可以将检测报告写入到文件

  (1)如果是C API,include leaktracer.h

  (2)如果是C++ API,include MemoryTrace.hpp


3.检测报告分析

  (1)推荐使用gdb

  (2)使用addr2line,如果泄露发生在so文件中,那么不能找到行信息了


4.官方的示例代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include "MemoryTrace.hpp"


char *doAlloc(unsigned int size);


int main()
{
	// startup part of the program
	// following allocation is not registered
	char *lostAtStartup = doAlloc(128); strcpy(lostAtStartup, "Lost at startup");

	// starting monitoring allocations
	leaktracer::MemoryTrace::GetInstance().startMonitoringAllThreads();
	char *memLeak = doAlloc(256); strcpy(memLeak, "This is a real memory leak");
	char *notLeak = doAlloc(64); strcpy(notLeak, "This is NOT a memory leak");

	char *memLeak2 = (char*)malloc(256); strcpy(memLeak2, "This is a malloc memory leak");
	free(lostAtStartup);

//	while (1)
//		wait();

	// stop monitoring allocations, but do still
	// monitor releases of the memory
	leaktracer::MemoryTrace::GetInstance().stopMonitoringAllocations();
	delete[] notLeak;
	notLeak = doAlloc(32);

	// stop all monitoring, print report
	leaktracer::MemoryTrace::GetInstance().stopAllMonitoring();

	std::ofstream oleaks;
	oleaks.open("leaks.out", std::ios_base::out);
	if (oleaks.is_open())
		leaktracer::MemoryTrace::GetInstance().writeLeaks(oleaks);
	else
		std::cerr << "Failed to write to \"leaks.out\"\n";

	return 0;
}


char *doAlloc(unsigned int size) {
	return new char[size];
}


5.头文件申明的函数

<span style="white-space:pre">	</span>/** starts monitoring memory allocations in all threads */
	inline void startMonitoringAllThreads(void);
	/** starts monitoring memory allocations in current thread */
	inline void startMonitoringThisThread(void);

	/** stops monitoring memory allocations (in all threads or in
	 *   this thread only, depends on the function used to start
	 *   monitoring */
	inline void stopMonitoringAllocations(void);

	/** stops all monitoring - both of allocations and releases */
	inline void stopAllMonitoring(void);
<span style="white-space:pre">	</span>/** writes report with all memory leaks */
	void writeLeaks(std::ostream &out);

	/** writes report with all memory leaks */
	void writeLeaksToFile(const char* reportFileName);




 类似资料: