Browse Source

mem: add allocations and frees counters with u_mem_get_counters()

congestion
Evgeny 6 months ago
parent
commit
cfd1e53ee9
  1. 15
      lib/mem.c
  2. 1
      lib/mem.h

15
lib/mem.c

@ -50,6 +50,8 @@ static void init_mutex() {
static void* allocated_head = NULL; static void* allocated_head = NULL;
static size_t allocated_count = 0; static size_t allocated_count = 0;
static size_t allocations_count = 0;
static size_t frees_count = 0;
static void hex_dump(const void* mem, size_t len) { static void hex_dump(const void* mem, size_t len) {
const uint8_t* data = (const uint8_t*)mem; const uint8_t* data = (const uint8_t*)mem;
@ -138,6 +140,7 @@ void* u_malloc_impl(uint32_t size, const char* location) {
*next_ptr = allocated_head; *next_ptr = allocated_head;
allocated_head = base; allocated_head = base;
allocated_count++; allocated_count++;
allocations_count++;
UNLOCK(); UNLOCK();
return prefix_start + BOUNDARY_CHECK_SIZE + 8; return prefix_start + BOUNDARY_CHECK_SIZE + 8;
} }
@ -183,6 +186,7 @@ void u_free_impl(void* ptr, const char* location) {
allocated_head = *(void**)((uint8_t*)curr + NEXT_OFFSET); allocated_head = *(void**)((uint8_t*)curr + NEXT_OFFSET);
} }
allocated_count--; allocated_count--;
frees_count++;
found = true; found = true;
break; break;
} }
@ -205,11 +209,22 @@ char* u_strdup_impl(const char* s, const char* location) {
return copy; return copy;
} }
void u_mem_get_counters(size_t* allocations, size_t* frees, size_t* allocated) {
LOCK();
if (allocations) *allocations = allocations_count;
if (frees) *frees = frees_count;
if (allocated) *allocated = allocated_count;
UNLOCK();
}
void u_report_unfreed_blocks(void) { void u_report_unfreed_blocks(void) {
LOCK(); LOCK();
size_t count = allocated_count; size_t count = allocated_count;
void* head = allocated_head; void* head = allocated_head;
size_t alloc_count = allocations_count;
size_t free_count = frees_count;
UNLOCK(); UNLOCK();
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "Memory stats: allocations=%zu, frees=%zu, current=%zu", alloc_count, free_count, count);
if (count == 0) { if (count == 0) {
DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "No unfreed memory blocks."); DEBUG_INFO(DEBUG_CATEGORY_MEMORY, "No unfreed memory blocks.");
return; return;

1
lib/mem.h

@ -23,6 +23,7 @@ void* u_calloc_impl(uint32_t nmemb, uint32_t size, const char* location);
void* u_realloc_impl(void* ptr, uint32_t size, const char* location); void* u_realloc_impl(void* ptr, uint32_t size, const char* location);
void u_free_impl(void* ptr, const char* location); void u_free_impl(void* ptr, const char* location);
char* u_strdup_impl(const char* s, const char* location); char* u_strdup_impl(const char* s, const char* location);
void u_mem_get_counters(size_t* allocations, size_t* frees, size_t* allocated);
void u_report_unfreed_blocks(void); void u_report_unfreed_blocks(void);
#ifdef __cplusplus #ifdef __cplusplus
} }

Loading…
Cancel
Save