diff --git a/rational.c b/rational.c index 439f9673da..f6c49fe516 100644 --- a/rational.c +++ b/rational.c @@ -261,10 +261,15 @@ rb_gcd_gmp(VALUE x, VALUE y) mpz_gcd(mz, mx, my); + mpz_clear(mx); + mpz_clear(my); + zn = (mpz_sizeinbase(mz, 16) + SIZEOF_BDIGIT*2 - 1) / (SIZEOF_BDIGIT*2); z = rb_big_new(zn, 1); mpz_export(BIGNUM_DIGITS(z), &count, -1, sizeof(BDIGIT), 0, nails, mz); + mpz_clear(mz); + return rb_big_norm(z); } #endif diff --git a/test/ruby/test_rational.rb b/test/ruby/test_rational.rb index 9651f46f01..e40de141b5 100644 --- a/test/ruby/test_rational.rb +++ b/test/ruby/test_rational.rb @@ -880,6 +880,16 @@ class Rational_Test < Test::Unit::TestCase assert_equal(1152921470247108503, 1073741789.lcm(1073741827)) end + def test_gcd_no_memory_leak + assert_no_memory_leak([], "#{<<-"begin;"}", "#{<<-"end;"}", limit: 1.2, rss: true) + x = (1<<121) + 1 + y = (1<<99) + 1 + 1000.times{x.gcd(y)} + begin; + 100.times {1000.times{x.gcd(y)}} + end; + end + def test_supp assert_predicate(1, :real?) assert_predicate(1.1, :real?)