Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Created January 15, 2023 22:30
Show Gist options
  • Save Infinitusvoid/e80e3a7686a2eb1cbacb8342a694e096 to your computer and use it in GitHub Desktop.
Save Infinitusvoid/e80e3a7686a2eb1cbacb8342a694e096 to your computer and use it in GitHub Desktop.
C++ : How to track memory allocations in code?
#include <iostream>
#include <memory>
// we override the new operator globally
// By overring the new operator we ara saying don't use the new operator that is in the standard library
struct AllocationMetrics
{
uint32_t total_allocated = 0;
uint32_t total_freed = 0;
uint32_t CurrectUsage()
{
return total_allocated - total_freed;
}
};
static AllocationMetrics s_Allocation_metrics;
void* operator new(size_t size)
{
s_Allocation_metrics.total_allocated += size;
return malloc(size);
}
void operator delete(void* memory, size_t size)
{
s_Allocation_metrics.total_freed += size;
free(memory);
}
static void print_memory_usage()
{
std::cout << "Memory usage: " << s_Allocation_metrics.CurrectUsage() << " bytes\n";
}
struct MyObject
{
int x, y, z;
};
void run()
{
print_memory_usage();
std::string string = "Some text";
print_memory_usage();
{
std::unique_ptr<MyObject> obj2 = std::make_unique<MyObject>(); //if you use smart pointers works as well
print_memory_usage();
}
print_memory_usage();
MyObject* obj = new MyObject;
delete obj;
print_memory_usage();
}
int main()
{
run();
print_memory_usage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment