EXC_BAD_ACCESS in boxed closure

⚓ Rust    📅 2025-05-04    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 109 days ago. The information described in this article may have changed.

I have some code in a complex application which roughly looks like this (all main thread only)

let callback: RefCell<Box<dyn Fn()>> = ...;

// RcBlock here is an obj-c callback block.
// this is not the core of the issue (but may be part of it)
// as it works fine when not using the `callback`  var.
let other_fn = RcBlock(|| {
   callback.borrow()();
})

// this is just to symbolise that we are no longer the owner of this
// `other_fn` and that the os will call the callback from the main thread
// note that `callback` is never dropped
dispatch(other_fn);

This works on all targets I tested, except on iOS where I got a EXC_BAD_ACCESS with the stack trace leading me to boxed.rs:

#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
    extern "rust-call" fn call(&self, args: Args) -> Self::Output {
        <F as Fn<Args>>::call(self, args)
    }
}

which I presume is the internal call implementation of a boxed closure. It is really odd to me why this happens, but maybe someone can shed some light onto this.

Edit: I found that it is refcell related, but I also find it hard to believe that it's a lifetime issue.

3 posts - 3 participants

Read full topic

🏷️ rust_feed