mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
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 <gemini@google.com>
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user