title: How can I free memory allocated by Rust code exposed in WebAssembly?
body: <p>I have a web application written in Rust and wasm-bindgen that needs to store state. The state is stored like this:</p>
  
  <pre><code>lazy_static! {
      static ref ID_TO_DATA: Mutex&lt;HashMap&lt;u32, Data&gt;&gt; = Mutex::new(HashMap::new());
  }
  
  pub struct Data {
      pub coder_id: u16,
      pub bools: Vec&lt;bool&gt;,
      pub ints: Vec&lt;i32&gt;,
      pub strings: Vec&lt;String&gt;,
  }
  </code></pre>
  
  <p>I attempted the following to remove the data and free the memory, and the data is removed from the <code>HashMap</code> and no errors are reported:</p>
  
  <pre><code>#[wasm_bindgen]
  pub fn remove_data(id: u32) {
      match ID_TO_DATA.lock().unwrap().remove(&amp;id) {
          Some(data) =&gt; {
              std::mem::drop(data);
          }
          None =&gt; {}
      }
  }
  </code></pre>
  
  <p>However, the memory used by the browser tab never drops (using Chrome 67). I used Windows' Task Manager and watched the memory grow to almost 2GB for the relevant process/tab, and then after my program removed all the entries, I waited a minute and the memory was still at almost 2GB.</p>
  
  <p>I also tried the following, but got this error: <code>RuntimeError: memory access out of bounds</code></p>
  
  <pre><code>#[wasm_bindgen]
  pub fn remove_data(id: u32) {
      match ID_TO_DATA.lock().unwrap().remove(&amp;id) {
          Some(mut data) =&gt; {
              unsafe {
                  std::ptr::drop_in_place(&amp;mut data);
              }
          }
          None =&gt; {}
      }
  }
  </code></pre>
  
  <p>How can I successfully free this memory?</p>