allocation_counter.cc (2015B)
1 /* 2 * Copyright (c) 2025 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #include "common_audio/allocation_counter.h" 12 13 #if defined(WEBRTC_ALLOCATION_COUNTER_AVAILABLE) 14 15 #include <cstddef> 16 #include <cstdlib> 17 #include <vector> 18 19 #include "absl/base/attributes.h" 20 #include "test/gtest.h" 21 22 namespace { 23 #if defined(ABSL_HAVE_THREAD_LOCAL) 24 ABSL_CONST_INIT thread_local size_t g_new_count = 0u; 25 ABSL_CONST_INIT thread_local size_t g_delete_count = 0u; 26 #elif defined(WEBRTC_POSIX) 27 #error Handle WEBRTC_POSIX 28 #else 29 #error Unsupported platform 30 #endif 31 } // namespace 32 33 void* operator new(size_t s) { 34 ++g_new_count; 35 return malloc(s); 36 } 37 38 void* operator new[](size_t s) { 39 ++g_new_count; 40 return malloc(s); 41 } 42 43 void operator delete(void* p) throw() { 44 ++g_delete_count; 45 return free(p); 46 } 47 48 void operator delete[](void* p) throw() { 49 ++g_delete_count; 50 return free(p); 51 } 52 53 namespace webrtc { 54 55 AllocationCounter::AllocationCounter() 56 : initial_new_count_(g_new_count), initial_delete_count_(g_delete_count) {} 57 58 size_t AllocationCounter::new_count() const { 59 return g_new_count - initial_new_count_; 60 } 61 62 size_t AllocationCounter::delete_count() const { 63 return g_delete_count - initial_delete_count_; 64 } 65 66 TEST(AllocationCounterTest, CountsHeapAllocations) { 67 std::vector<int> v; 68 AllocationCounter counter; 69 EXPECT_EQ(counter.new_count(), 0u); 70 EXPECT_EQ(counter.delete_count(), 0u); 71 v.resize(1000); 72 EXPECT_EQ(counter.new_count(), 1u); 73 EXPECT_EQ(counter.delete_count(), 0u); 74 v.clear(); 75 v.shrink_to_fit(); 76 EXPECT_EQ(counter.new_count(), 1u); 77 EXPECT_EQ(counter.delete_count(), 1u); 78 } 79 80 } // namespace webrtc 81 82 #endif // defined(WEBRTC_ALLOCATION_COUNTER_AVAILABLE)