32 return std::lower_bound(t.begin(), t.end(), addr,
33 [](
const AllocationInfo& a, std::uintptr_t k){ return a.ptr < k; });
38static inline std::uintptr_t key_of(
const void* p)
noexcept {
39 return reinterpret_cast<std::uintptr_t
>(p);
51 static auto* m =
new std::vector<AllocationInfo>();
62 static auto* mu =
new std::mutex();
75inline void on_alloc(
const void* ptr, std::size_t sz) {
84 std::scoped_lock _(
lock());
86 const auto addr = key_of(ptr);
89 if (it !=
table().end() && it->ptr == addr) {
108 if (!g.
armed)
return;
110 std::scoped_lock lk(
lock());
112 const auto addr = key_of(ptr);
115 if (it != t.end() && it->ptr == addr) {
126[[nodiscard]]
inline bool isLive(
const void* ptr) {
127 std::scoped_lock lk(
lock());
128 const auto& t =
table();
129 const auto addr = key_of(ptr);
132 return it != t.end() && it->ptr == addr;
144 std::scoped_lock g(
lock());
145 std::size_t total_bytes = 0;
148 for (
const auto& info :
table()) {
150 os <<
"[" << i++ <<
"] LEAK " <<
reinterpret_cast<void*
>(info.ptr) <<
" (" << info.size <<
" bytes)\n";
151 total_bytes += info.size;
153 os <<
"[SUMMARY] " << i <<
" potential leak(s), total " << total_bytes <<
" bytes.\n";
165 std::scoped_lock g(
lock());
167 for (
const auto& info :
table()) {
168 os <<
"[" << i++ <<
"] LIVE " <<
reinterpret_cast<void*
>(info.ptr) <<
" (" << info.size <<
" bytes)\n";
auto lower_bound_addr(std::vector< AllocationInfo > &t, std::uintptr_t addr)
Definition MemoryTracker.hpp:31
thread_local bool in_hook
Definition MemoryTracker.hpp:18
Definition BitCaster.hpp:5
std::mutex & lock()
Access the global mutex used to protect the table.
Definition MemoryTracker.hpp:61
auto & table()
Access the singleton allocation table.
Definition MemoryTracker.hpp:50
void printAllocationLog(std::ostream &os=std::cout)
Print all currently tracked allocations.
Definition MemoryTracker.hpp:164
void reportLeaks(std::ostream &os=std::cout)
Print a summary of all currently live allocations (potential leaks).
Definition MemoryTracker.hpp:143
bool isLive(const void *ptr)
Check if a pointer is currently tracked as allocated.
Definition MemoryTracker.hpp:126
void on_alloc(const void *ptr, std::size_t sz)
Register a new allocation.
Definition MemoryTracker.hpp:75
void on_free(const void *ptr)
Unregister a freed allocation.
Definition MemoryTracker.hpp:105
Definition MemoryTracker.hpp:13
std::uintptr_t ptr
Definition MemoryTracker.hpp:14
std::size_t size
Definition MemoryTracker.hpp:15
Definition MemoryTracker.hpp:20
bool armed
Definition MemoryTracker.hpp:21
~HookGuard()
Definition MemoryTracker.hpp:25
HookGuard()
Definition MemoryTracker.hpp:22