-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentinel.cpp
More file actions
64 lines (51 loc) · 1.68 KB
/
Sentinel.cpp
File metadata and controls
64 lines (51 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include "Sentinel.h"
#include <unordered_map>
#include <mutex>
namespace {
struct AllocationInfo{
std::size_t size;
std::string file;
int line;
};
// Tracks active allocations
std::unordered_map<void*, AllocationInfo> allocations;
// Ensures thread-safe access to the allocation tracker
std::mutex allocMutex;
}
namespace Sentinel {
// Allocates memory and registers the allocation for tracking
void* allocate(std::size_t size, const char* file, int line){
void* ptr = std::malloc(size);
if (!ptr) throw std::bad_alloc{};
// Protect shared allocation map
std::lock_guard<std::mutex> lock(allocMutex);
allocations[ptr] = { size, file, line };
return ptr;
}
void deallocate(void* ptr){
if (!ptr) return;
std::lock_guard<std::mutex> lock(allocMutex);
auto it = allocations.find(ptr);
if (it == allocations.end()){
std::cerr << "[Sentinel] WARNING: Freeing unknown pointer: " << ptr << "\n";
return;
}
allocations.erase(it);
std::free(ptr);
}
void reportLeaks(){
std::lock_guard<std::mutex> lock(allocMutex);
if (allocations.empty()){
std::cout << "[Sentinel] No memory leaks detected.\n";
return;
}
std::cout << "\n[Sentinel] MEMORY LEAKS DETECTED:\n";
for (const auto& [ptr, info] : allocations){
std::cout << " - Leak at " << ptr
<< " | Size: " << info.size
<< " bytes | Location: "
<< info.file << ":" << info.line << "\n";
}
}
}