Skip to content

Commit 1f767f4

Browse files
committed
Overload new and new[]
1 parent fb1ddc3 commit 1f767f4

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

tests/runtime_tests.cpp

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// Allocation tracker, to catch memory leaks and double delete
77
constexpr std::size_t max_allocations = 20'000;
88
void* allocations[max_allocations];
9+
void* allocations_array[max_allocations];
910
std::size_t num_allocations = 0u;
1011
std::size_t double_delete = 0u;
1112
bool memory_tracking = false;
@@ -28,20 +29,25 @@ void* allocate(std::size_t size, bool array) {
2829
}
2930

3031
if (memory_tracking) {
31-
allocations[num_allocations] = p;
32+
if (array) {
33+
allocations_array[num_allocations] = p;
34+
} else {
35+
allocations[num_allocations] = p;
36+
}
37+
3238
++num_allocations;
3339
}
3440

3541
return p;
3642
}
3743

38-
void operator delete(void* p) noexcept
39-
{
44+
void deallocate(void* p, bool array) {
4045
if (memory_tracking) {
4146
bool found = false;
47+
void** allocations_type = array ? allocations_array : allocations;
4248
for (std::size_t i = 0; i < num_allocations; ++i) {
43-
if (allocations[i] == p) {
44-
std::swap(allocations[i], allocations[num_allocations-1]);
49+
if (allocations_type[i] == p) {
50+
std::swap(allocations_type[i], allocations_type[num_allocations-1]);
4551
--num_allocations;
4652
found = true;
4753
break;
@@ -55,6 +61,22 @@ void operator delete(void* p) noexcept
5561

5662
std::free(p);
5763
}
64+
65+
void* operator new(std::size_t size) {
66+
return allocate(size, false);
67+
}
68+
69+
void* operator new[](size_t size) {
70+
return allocate(size, true);
71+
}
72+
73+
void operator delete(void* p) noexcept {
74+
deallocate(p, false);
75+
}
76+
77+
void operator delete[](void* p) noexcept {
78+
deallocate(p, true);
79+
}
5880
#endif
5981

6082
struct memory_tracker {

0 commit comments

Comments
 (0)