From e3e9739f04976f65804c01a747ea0cef14bdabb9 Mon Sep 17 00:00:00 2001 From: Nora Widdecke Date: Mon, 1 Mar 2021 22:45:46 +0100 Subject: ffi: Fix memory leak. - When dropping the Context, free the error pointer, too. - Add test that would have allowed valgrind to find the issue. - Fixes #671 --- ffi/src/core.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'ffi') diff --git a/ffi/src/core.rs b/ffi/src/core.rs index d0dd5138..a24c2137 100644 --- a/ffi/src/core.rs +++ b/ffi/src/core.rs @@ -61,6 +61,16 @@ impl Context { } } +impl Drop for Context { + fn drop(&mut self) { + if !self.e.is_null() { + unsafe { + drop(Box::from_raw(self.e)); + } + } + } +} + /// Returns the last error. /// /// Returns and removes the last error from the context. @@ -173,3 +183,19 @@ fn sq_config_ephemeral(cfg: *mut Config) { let cfg = ffi_param_ref_mut!(cfg); cfg.set_ephemeral(); } + +#[test] +fn test_drop_context() { + { + use crate::MoveIntoRaw; + + let c = sq_context_new(None); + let ctx = ffi_param_ref_mut!(c); + let errp = ctx.errp(); + { + let e = anyhow::anyhow!("bad"); + *errp = e.move_into_raw(); + } + sq_context_free(Some(ctx)); + } +} -- cgit v1.2.3