From 64886fd9655639ecc5a9c85f4aaba3e4423ced75 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Tue, 12 Aug 2025 13:35:18 +0900 Subject: [PATCH] mruby-random: use mrb_alloca in mrb_ary_sample to prevent memory leak Refactor mrb_ary_sample to use mrb_alloca for the 'idx' array. This ensures that the memory is automatically freed when the C function returns, preventing a memory leak if an exception is raised during array manipulation. Co-authored-by: Gemini --- mrbgems/mruby-random/src/random.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mrbgems/mruby-random/src/random.c b/mrbgems/mruby-random/src/random.c index 437af55eb..2530fea4e 100644 --- a/mrbgems/mruby-random/src/random.c +++ b/mrbgems/mruby-random/src/random.c @@ -479,7 +479,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary) if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, "negative sample number"); if (n > len) n = len; /* collect unique indices without allocating Ruby Integers */ - mrb_int *idx = (mrb_int*)mrb_malloc(mrb, sizeof(mrb_int) * (n > 0 ? n : 1)); + mrb_int *idx = (mrb_int*)mrb_alloca(mrb, sizeof(mrb_int) * (n > 0 ? n : 1)); for (mrb_int i = 0; i < n; i++) { mrb_int v; for (;;) { @@ -496,7 +496,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary) for (mrb_int i = 0; i < n; i++) { mrb_ary_push(mrb, result, RARRAY_PTR(ary)[idx[i]]); } - mrb_free(mrb, idx); + return result; } }