From 00cd93ac61096eda8eaed75628fc469b20d980e5 Mon Sep 17 00:00:00 2001 From: HeatCraB Date: Sun, 30 Mar 2025 03:36:11 +0800 Subject: [PATCH] Improve dudect test with memory leak fix Valgrind inspection revealed memory leaks in the original code, with 43,632 bytes lost across 909 blocks per test. Analysis showed that the initialization function was being called repeatedly within the testing loop, each time reallocating the context array without any provision to free prior memory allocations. This uncontrolled repetition caused memory to accumulate not freed over multiple test iterations, leading to the observed leaks. To correct this, the initialization process was revised to execute only once before testing begins, and a cleanup was added to release all allocated memory when testing concludes. To further prevent memory-related issues, the measurement function was updated to check all memory allocations, ensuring robustness against potential failures. Change-Id: Id5e7b24447cb5b7797ef19c4bfdb79060fb299fa --- dudect/fixture.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/dudect/fixture.c b/dudect/fixture.c index 65d6ae4c9..c2e273a7a 100644 --- a/dudect/fixture.c +++ b/dudect/fixture.c @@ -187,7 +187,7 @@ static bool doit(int mode) int64_t *percentiles = calloc(NUM_PERCENTILES, sizeof(int64_t)); if (!before_ticks || !after_ticks || !exec_times || !classes || - !input_data) { + !input_data || !percentiles) { die(); } @@ -213,8 +213,13 @@ static void init_once(void) { init_dut(); for (size_t i = 0; i < DUDECT_TESTS; i++) { - ctxs[i] = malloc(sizeof(t_context_t)); - t_init(ctxs[i]); + /* Check if ctxs[i] is unallocated to prevent repeated memory + * allocations. + */ + if (!ctxs[i]) { + ctxs[i] = malloc(sizeof(t_context_t)); + t_init(ctxs[i]); + } } } @@ -222,9 +227,10 @@ static bool test_const(char *text, int mode) { bool result = false; + init_once(); + for (int cnt = 0; cnt < TEST_TRIES; ++cnt) { printf("Testing %s...(%d/%d)\n\n", text, cnt, TEST_TRIES); - init_once(); for (int i = 0; i < ENOUGH_MEASURE / (N_MEASURES - DROP_SIZE * 2) + 1; ++i) result = doit(mode); @@ -235,6 +241,7 @@ static bool test_const(char *text, int mode) for (size_t i = 0; i < DUDECT_TESTS; i++) { free(ctxs[i]); + ctxs[i] = NULL; } return result;