手写Linux环境下C++内存泄漏检测

撸代码

#include 
#include 
#include 
#include 
#include 

std::mutex _mapLock;
//std::map _pointerNewMap;

struct TPair
{
	bool bOccupy = false;
	const void* memPtr = 0;
	const void* operatorRetAddr = 0;
};

TPair mapData[4*1024*1024];

void* operator new(std::size_t sz)
{
	if (sz == 0)
		++sz;

	if (void* ptr=std::malloc(sz))
	{
		_mapLock.lock();
		
		//引起递归调用这个new操作符函数
		//_pointerNewMap[ptr] = __builtin_return_address(0);
		//_pointerNewMap.insert(std::pair(ptr, __builtin_return_address(0)));
		for (int i = 0; i < 4 * 1024*1024; i++)
		{
			if(mapData[i].bOccupy == false)
			{
				mapData[i].bOccupy = true;
				mapData[i].memPtr = ptr;
				mapData[i].operatorRetAddr = __builtin_return_address(0);
				break;
			}
		}

		_mapLock.unlock();
		return ptr;
	}

	throw std::bad_alloc();
}

void operator delete(void* ptr) noexcept
{
	_mapLock.lock();
	for (int i = 0; i < 4 * 1024 * 1024; i++)
	{
		if(mapData[i].memPtr == ptr)
		{
			mapData[i].bOccupy = false;
		}
	}
	_mapLock.unlock();
	std::free(ptr);
}

void func()
{
	int* xx = new int[126];
	return;
}

int main()
{
	int* n = new int;
	func();
	delete n;


	for (int i = 0; i < 4 * 1024 * 1024; i++)
	{
		if (mapData[i].bOccupy)
		{
			char syscom[256];
			sprintf(syscom, "addr2line %p -e a.out", mapData[i].operatorRetAddr);
			system(syscom);
		}
	}
	
	return 0;
}

编译

g++ MemLeakTest.cpp -g -o a.out
 

你可能感兴趣的:(C++,Linux使用,c++,算法,开发语言)