From e5039cdefcf5268f900d8199da3d6cfb0d8adbb8 Mon Sep 17 00:00:00 2001 From: Shizuo Fujita Date: Tue, 23 Dec 2025 14:57:41 +0900 Subject: [PATCH] Fix potential memory leak if zstd_compress fails This PR fixes a potential memory leak in the compression path. In the current implementation, if zstd_compress returns an error, rb_raise is called immediately. If rb_raise will be called, the subsequent ZSTD_freeCCtx(ctx) is never reached. This change ensures that ZSTD_freeCCtx(ctx) is called before raising the exception, preventing the context leak. Seems zstd_compress errors are rare in practice, this fix ensures safety for those edge cases. --- ext/zstdruby/zstdruby.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/zstdruby/zstdruby.c b/ext/zstdruby/zstdruby.c index 1d41522..5ce10c6 100644 --- a/ext/zstdruby/zstdruby.c +++ b/ext/zstdruby/zstdruby.c @@ -30,12 +30,12 @@ static VALUE rb_compress(int argc, VALUE *argv, VALUE self) char* output_data = RSTRING_PTR(output); size_t const ret = zstd_compress(ctx, output_data, max_compressed_size, input_data, input_size, false); + ZSTD_freeCCtx(ctx); if (ZSTD_isError(ret)) { rb_raise(rb_eRuntimeError, "compress error error code: %s", ZSTD_getErrorName(ret)); } rb_str_resize(output, ret); - ZSTD_freeCCtx(ctx); return output; }