From f195d1d91e56187e136106e39fce8197c6f8610c Mon Sep 17 00:00:00 2001 From: Evgeny Date: Tue, 21 Apr 2026 02:26:27 +0300 Subject: [PATCH] Memory: refactor hex_dump to use buffer with DEBUG output --- lib/mem.c | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/lib/mem.c b/lib/mem.c index 169ff981..878d42fa 100644 --- a/lib/mem.c +++ b/lib/mem.c @@ -51,27 +51,29 @@ static void init_mutex() { static void* allocated_head = NULL; static size_t allocated_count = 0; -static void hex_dump(const void* mem, size_t len) { +static void hex_dump_buf(const void* mem, size_t len, char* buf, size_t buf_size) { const uint8_t* data = (const uint8_t*)mem; - for (size_t i = 0; i < len; i += 16) { - printf("%08zx: ", i); + size_t off = 0; + for (size_t i = 0; i < len && i < 256; i += 16) { + if (off >= buf_size - 80) break; + off += snprintf(buf + off, buf_size - off, "%08zx: ", i); for (size_t j = 0; j < 16; j++) { if (i + j < len) { - printf("%02x ", data[i + j]); + off += snprintf(buf + off, buf_size - off, "%02x ", data[i + j]); } else { - printf(" "); + off += snprintf(buf + off, buf_size - off, " "); } } - printf(" "); + off += snprintf(buf + off, buf_size - off, " "); for (size_t j = 0; j < 16; j++) { if (i + j < len) { uint8_t c = data[i + j]; - printf("%c", (c >= 32 && c <= 126) ? c : '.'); + off += snprintf(buf + off, buf_size - off, "%c", (c >= 32 && c <= 126) ? c : '.'); } else { - printf(" "); + off += snprintf(buf + off, buf_size - off, " "); } } - printf("\n"); + off += snprintf(buf + off, buf_size - off, "\n"); } } @@ -115,7 +117,9 @@ void u_check(void* ptr, const char* text, const char* location) { printf("%s: %s: Allocated at: %s\n", location, text, alloc_loc); printf("%s: %s: Memory block size (user): %u bytes, total allocated: %u bytes\n", location, text, size, total); printf("%s: %s: Full memory dump at base %p:\n", location, text, base); - hex_dump(base, total); + char dump_buf[4096]; + hex_dump_buf(base, total, dump_buf, sizeof(dump_buf)); + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "%s", dump_buf); exit(EXIT_FAILURE); } } @@ -227,7 +231,9 @@ void u_report_unfreed_blocks(void) { u_check(user_ptr, "unfreed_check", "u_report_unfreed_blocks"); DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, " - Allocated at: %s, size: %u bytes\n", alloc_loc, size); DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, " Full memory dump at %p:\n", user_ptr); - hex_dump(user_ptr, size); + char dump_buf[4096]; + hex_dump_buf(user_ptr, size, dump_buf, sizeof(dump_buf)); + DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "%s", dump_buf); curr = *(void**)((uint8_t*)curr + NEXT_OFFSET); } }