Created
January 15, 2023 22:30
-
-
Save Infinitusvoid/e80e3a7686a2eb1cbacb8342a694e096 to your computer and use it in GitHub Desktop.
C++ : How to track memory allocations in code?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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