From d09118ee4512c76796cc9c06bc5136ae99a0b101 Mon Sep 17 00:00:00 2001 From: jonathantanmy Date: Fri, 26 Jul 2024 04:52:56 -0700 Subject: [PATCH] myers: avoid a Miri-flagged pointer invalidation (#10) In Myers::new, the kforward and kbackward pointers (derived from kvec) are invalidated by a subsequent kvec.into() (into a pointer). This can be seen by copying the relevant code into the Rust playground and running it under Miri [1]. To fix this, make kvec a pointer from the start. [1] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=554abe93817c3d95a3412006e8efb022 --- This was my attempt at fixing this - feel free to rewrite to fit your project's coding style if you like. --- src/myers.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/myers.rs b/src/myers.rs index 061b93d..027cd98 100644 --- a/src/myers.rs +++ b/src/myers.rs @@ -53,11 +53,15 @@ impl Drop for Myers { impl Myers { fn new(len1: usize, len2: usize) -> Self { let ndiags = len1 + len2 + 3; - let kvec = Box::leak(vec![0; 2 * ndiags + 2].into_boxed_slice()); - let kforward = NonNull::from(&mut kvec[len2 + 1]); - let kbackward = NonNull::from(&mut kvec[ndiags + len2 + 1]); + let kvec: *mut [i32] = Box::into_raw(vec![0; 2 * ndiags + 2].into_boxed_slice()).into(); + let (kforward, kbackward) = unsafe { + ( + NonNull::new_unchecked((kvec as *mut i32).offset((len2 + 1) as isize)), + NonNull::new_unchecked((kvec as *mut i32).offset((ndiags + len2 + 1) as isize)), + ) + }; Self { - kvec: kvec.into(), + kvec: unsafe { NonNull::new_unchecked(kvec) }, kforward, kbackward, max_cost: sqrt(ndiags).max(MAX_COST_MIN),