From 6fc4f9e07ef9a3cabbb0b26fac123557621c3b69 Mon Sep 17 00:00:00 2001 From: Peter Zhu Date: Mon, 5 Feb 2024 15:01:51 -0500 Subject: [PATCH] Fix memory leak in util_spec_rb_get_kwargs The call to rb_get_kwargs could raise an exception, which would cause the ids and results to be leaked. This commit changes these two to be allocated on the stack using alloca instead of malloc so we don't need to free it. --- optional/capi/ext/util_spec.c | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/optional/capi/ext/util_spec.c b/optional/capi/ext/util_spec.c index 95ba71ea9d..42365884a8 100644 --- a/optional/capi/ext/util_spec.c +++ b/optional/capi/ext/util_spec.c @@ -62,22 +62,17 @@ static VALUE util_spec_rb_get_kwargs(VALUE self, VALUE keyword_hash, VALUE keys, int len = RARRAY_LENINT(keys); int values_len = req + (opt < 0 ? -1 - opt : opt); - int i = 0; - ID *ids = (ID*) malloc(sizeof(VALUE) * len); - VALUE *results = (VALUE*) malloc(sizeof(VALUE) * values_len); - int extracted = 0; - VALUE ary = Qundef; + ID *ids = alloca(sizeof(VALUE) * len); + VALUE *results = alloca(sizeof(VALUE) * values_len); - for (i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { ids[i] = SYM2ID(rb_ary_entry(keys, i)); } - extracted = rb_get_kwargs(keyword_hash, ids, req, opt, results); - ary = rb_ary_new_from_values(extracted, results); - free(results); - free(ids); - return ary; + int extracted = rb_get_kwargs(keyword_hash, ids, req, opt, results); + + return rb_ary_new_from_values(extracted, results); } static VALUE util_spec_rb_long2int(VALUE self, VALUE n) {