From 2512b4b399eb50ce61ecf6873b3e7f3f650ca61c Mon Sep 17 00:00:00 2001 From: dearblue Date: Sun, 26 Oct 2025 16:29:06 +0900 Subject: [PATCH] Preventing Memory Leaks in `Array#__combination_init` If memory allocated with `mrb_malloc()` is not associated with an object, subsequent attempts to allocate memory or objects will fail and raise an exception, resulting in a memory leak. --- mrbgems/mruby-array-ext/src/array.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/mrbgems/mruby-array-ext/src/array.c b/mrbgems/mruby-array-ext/src/array.c index 426d95bb3..f765810c1 100644 --- a/mrbgems/mruby-array-ext/src/array.c +++ b/mrbgems/mruby-array-ext/src/array.c @@ -1316,7 +1316,13 @@ ary_combination_init(mrb_state *mrb, mrb_value self) mrb_get_args(mrb, "ib", &n, &permutation); + /* prepare objects in first to avoid memory leaks caused by NoMemoryError exceptions */ + struct RData *d = mrb_data_object_alloc(mrb, mrb->object_class, NULL, NULL); + struct mrb_combination_state *state = (struct mrb_combination_state*)mrb_malloc(mrb, sizeof(*state)); + d->data = state; + d->type = &mrb_combination_state_type; + state->indices = NULL; state->n = n; state->array_size = RARRAY_LEN(self); state->permutation = permutation; @@ -1328,11 +1334,8 @@ ary_combination_init(mrb_state *mrb, mrb_value self) state->indices[i] = 0; } } - else { - state->indices = NULL; - } - return mrb_obj_value(mrb_data_object_alloc(mrb, mrb->object_class, state, &mrb_combination_state_type)); + return mrb_obj_value(d); } /*