From 317a6aecc74e902f978c422038765d3f059648eb Mon Sep 17 00:00:00 2001 From: Shizuo Fujita Date: Tue, 23 Dec 2025 15:36:13 +0900 Subject: [PATCH] Fix memory leak with non-String object This PR fixes a memory leak that occurs when a non-string object is passed to Zstd.compress. If a non-string object was given, StringValue() will raise a TypeError. It causes memory leak. This patch moves the input validation before the context creation to prevent this leak. --- ext/zstdruby/zstdruby.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ext/zstdruby/zstdruby.c b/ext/zstdruby/zstdruby.c index 1d41522..d8fdc72 100644 --- a/ext/zstdruby/zstdruby.c +++ b/ext/zstdruby/zstdruby.c @@ -14,6 +14,8 @@ static VALUE rb_compress(int argc, VALUE *argv, VALUE self) VALUE kwargs; rb_scan_args(argc, argv, "10:", &input_value, &kwargs); + StringValue(input_value); + ZSTD_CCtx* const ctx = ZSTD_createCCtx(); if (ctx == NULL) { rb_raise(rb_eRuntimeError, "%s", "ZSTD_createCCtx error"); @@ -21,7 +23,6 @@ static VALUE rb_compress(int argc, VALUE *argv, VALUE self) set_compress_params(ctx, kwargs); - StringValue(input_value); char* input_data = RSTRING_PTR(input_value); size_t input_size = RSTRING_LEN(input_value);