Stdweb:: js! macro, memory leak on callback


Any callbacks passed into JavaScript will leak memory by default! You need to call .drop() on the callback from the JavaScript side to free it.

Can anyone explain how/why this happens? (And what the fix is.)

It happens because the JS side doesn't know if the wasm code is still using it, so it can't free it. If the closure stays in Rust, it will be dropped at the end of the scope as normal, but when passed to Javascript, you will need to manually drop it.

1 Like

@alice : I don't understand the following: Why is it that (1) the above argument works for Callbacks, but (2) does not hold for Objects ?

When I'm looking at the js! examples, when we pass a Object from rust to js, all it uses is js! { ... @{ ... obj .. } ... }

  1. rust/wasm32 does not know if js is still using Callback/Object
  2. therefore, js needs to manually call .drop on Callback/Object

Why is it that the above is true for Callback but unnecessary for Object? There is something fundamental here that I'm not understanding.

I don't actually know, I'm just going by the documentation. I'd guess that the difference is that the callbacks contain some wasm code while the objects do not?

bumping post

Can anyone else enlighten on difference of callbacks vs objects that results in needing to manually drop callbacks but not objects?