C Plus Plus 重新实现 new 和 delete实现内存泄漏检测

50 阅读1分钟
#include <memory>
#include <iostream>

class AllocManagement {
public:
	int allocSize;
	int freeSize;

	int retAllocSize() {
		return allocSize- freeSize;
	}
};

static AllocManagement m_AllocManagement;

void* operator new(size_t size) {
	std::cout << "Alloc Size : " << size << std::endl;
	m_AllocManagement.allocSize += size;
	return malloc(size);
}

void operator delete(void* memory, size_t size) {
	std::cout << "Free Size : " << size << std::endl;
	m_AllocManagement.freeSize += size;
	free(memory);
}


int main(int argc, char* argv[])
{ 
	{
		new int[10];
		std::string str = "1234567";
	}

	std::cout << "内存泄漏 : " << m_AllocManagement.retAllocSize();
}