Skip to content

Instantly share code, notes, and snippets.

@FangYang970206
Created March 11, 2020 14:11
Show Gist options
  • Save FangYang970206/cfaf858e3b9eeb5b95cebdf3d88937a0 to your computer and use it in GitHub Desktop.
Save FangYang970206/cfaf858e3b9eeb5b95cebdf3d88937a0 to your computer and use it in GitHub Desktop.
跟踪内存分配以及释放的方法,有助于检查是否有内存泄漏
#include <iostream>
#include <memory>
using namespace std;
struct AllocationMetrics{
uint32_t totalMemory = 0;
uint32_t totalFree = 0;
uint32_t getCurrentUsage() {return totalMemory - totalFree;}
};
static AllocationMetrics s_allocationMetrics;
void* operator new(size_t size){
cout << "Allocate " << size << " bytes\n";
s_allocationMetrics.totalMemory += size;
return malloc(size);
}
void operator delete(void* ptr, size_t size) {
cout << "Deallocate " << size << " bytes\n";
s_allocationMetrics.totalFree += size;
free(ptr);
}
struct ListNode{
int value;
ListNode* next;
};
int main(int argc, char* argv[])
{
{
auto pListNode = make_unique<ListNode>();
}
cout << "CurrentUsage: " << s_allocationMetrics.getCurrentUsage() << endl;
{
auto plistNode = new ListNode();
}
cout << "CurrentUsage: " << s_allocationMetrics.getCurrentUsage() << endl;
cin.ignore();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment