mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Fix segfault in Array#sample
This commit is contained in:
@@ -266,7 +266,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
|
||||
mrb_int n = 0;
|
||||
mrb_bool given;
|
||||
mt_state *random = NULL;
|
||||
mrb_int len = RARRAY_LEN(ary);
|
||||
mrb_int len;
|
||||
|
||||
mrb_get_args(mrb, "|i?d", &n, &given, &random, &mt_state_type);
|
||||
if (random == NULL) {
|
||||
@@ -274,6 +274,7 @@ mrb_ary_sample(mrb_state *mrb, mrb_value ary)
|
||||
}
|
||||
mrb_random_rand_seed(mrb, random);
|
||||
mt_rand(random);
|
||||
len = RARRAY_LEN(ary);
|
||||
if (!given) { /* pick one element */
|
||||
switch (len) {
|
||||
case 0:
|
||||
|
||||
@@ -74,3 +74,15 @@ assert('Array#shuffle!(random)') do
|
||||
|
||||
ary1 != [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and 10.times { |x| ary1.include? x } and ary1 == ary2
|
||||
end
|
||||
|
||||
assert('Array#sample checks input length after reading arguments') do
|
||||
$ary = [1, 2, 3]
|
||||
class ArrayChange
|
||||
def to_i
|
||||
$ary << 4
|
||||
4
|
||||
end
|
||||
end
|
||||
|
||||
assert_equal [1, 2, 3, 4], $ary.sample(ArrayChange.new).sort
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user