Skip to content

Commit 92fa4fb

Browse files
committed
Fix memory leaks in fixture.c
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: I5caf328015e6bba929b2c47068ba1b774985676c
1 parent f53314e commit 92fa4fb

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

Diff for: dudect/fixture.c

+15-11
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,17 @@ static bool report(void)
177177
return true;
178178
}
179179

180+
static void init_once(void)
181+
{
182+
init_dut();
183+
for (size_t i = 0; i < DUDECT_TESTS; i++) {
184+
if (!ctxs[i]) { // Avoid repeated allocation
185+
ctxs[i] = malloc(sizeof(t_context_t));
186+
t_init(ctxs[i]);
187+
}
188+
}
189+
}
190+
180191
static bool doit(int mode)
181192
{
182193
int64_t *before_ticks = calloc(N_MEASURES + 1, sizeof(int64_t));
@@ -187,7 +198,7 @@ static bool doit(int mode)
187198
int64_t *percentiles = calloc(NUM_PERCENTILES, sizeof(int64_t));
188199

189200
if (!before_ticks || !after_ticks || !exec_times || !classes ||
190-
!input_data) {
201+
!input_data || !percentiles) {
191202
die();
192203
}
193204

@@ -209,22 +220,14 @@ static bool doit(int mode)
209220
return ret;
210221
}
211222

212-
static void init_once(void)
213-
{
214-
init_dut();
215-
for (size_t i = 0; i < DUDECT_TESTS; i++) {
216-
ctxs[i] = malloc(sizeof(t_context_t));
217-
t_init(ctxs[i]);
218-
}
219-
}
220-
221223
static bool test_const(char *text, int mode)
222224
{
223225
bool result = false;
224226

227+
init_once(); // Initialize only once
228+
225229
for (int cnt = 0; cnt < TEST_TRIES; ++cnt) {
226230
printf("Testing %s...(%d/%d)\n\n", text, cnt, TEST_TRIES);
227-
init_once();
228231
for (int i = 0; i < ENOUGH_MEASURE / (N_MEASURES - DROP_SIZE * 2) + 1;
229232
++i)
230233
result = doit(mode);
@@ -235,6 +238,7 @@ static bool test_const(char *text, int mode)
235238

236239
for (size_t i = 0; i < DUDECT_TESTS; i++) {
237240
free(ctxs[i]);
241+
ctxs[i] = NULL;
238242
}
239243

240244
return result;

0 commit comments

Comments
 (0)