title: "RuntimeError : Memory access out of bounds" when trying to save a string in Wasm heap and then saving the pointer to the string in a struct
body: <p>I am trying to save a String in Wasm heap as <code>Uint8Array</code> after encoding and saving the pointer to the string and the length in a Struct so that i can access the string later. Below is My code in <code>rust</code></p>
  
  <pre><code>#[wasm_bindgen]
  pub struct CustomString{
      ptr : *const u8,
      len: usize
  }
  
  #[wasm_bindgen]
  impl CustomString{
      pub fn create(len:usize) -&gt; Self{
          let mut d = Vec::with_capacity(len);
          log!("{}",len);
  
          CustomString{
              ptr: d.as_ptr(),
              len
          }
      }
  
      pub fn as_ptr(&amp;self) -&gt; *const u8{
          self.ptr
      }
  
      pub fn print_string(&amp;self){
          let js = unsafe { std::slice::from_raw_parts(self.ptr, self.len) };
          let js = unsafe { std::str::from_utf8_unchecked(js) };
          log!("{}",js) 
      }
  }
  </code></pre>
  
  <p>My JS side code is as follows :</p>
  
  <pre><code>function myTest (){
      debugger;
      const { memory } = wasm;
      let encoder = new TextEncoder();
      let mystring = "Ujjal";
      let encodedString = encoder.encode(mystring);
  
      let length = encodedString.length;
      console.log(length)
  
      let cs = CustomString.create(length);
  
      let ptr = cs.as_ptr();
  
      const asBytes = new Uint8Array(memory.buffer, ptr, length);
  
      asBytes.set(encodedString);
  
      return cs;
  
  }
  
  let cs = myTest();
  
  
  function decode(cs){
  
      cs.print_string();
  }
  
  decode(cs);
  </code></pre>
  
  <p>Ideally it should print the given string but it shows some unrelated junk value. Couldn't figure what is going wrong as I am pretty new to rust and wasm. </p>
  
  <p>This is the console message I am getting when i run this and sometime Memory error.
  <a href="https://i.stack.imgur.com/a0xdI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a0xdI.png" alt="Console log"></a></p>