title: How can one force Rust to take ownership of memory allocated other than by its safe methods?
body: <p>In his February 2018 note titled "<a href="http://willcrichton.net/notes/rust-memory-safety/" rel="noreferrer">Memory Safety in Rust: 
  A Case Study with C</a>", Will Crichton wrote:</p>
  
  <blockquote>
    <p>Rust provides the ability to take ownership of raw pointers, which we do using <a href="https://doc.rust-lang.org/std/slice/fn.from_raw_parts_mut.html" rel="noreferrer"><code>slice::from_raw_parts_mut</code></a> and <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw" rel="noreferrer"><code>Box::from_raw</code></a> which tells Rust to treat the memory pointer as a heap-allocated array. After transferring ownership, assuming the memory is valid and of the right size/type, Rust applies its usual memory safety and containment checks.</p>
  </blockquote>
  
  <p>The relevant part of his code to which the above refers is:</p>
  
  <pre class="lang-rust prettyprint-override"><code>let mut new_data = unsafe {
      let ptr = Heap::default()
          .alloc(Layout::array::&lt;isize&gt;(new_capacity).unwrap())
          .unwrap() as *mut isize;
      Box::from_raw(slice::from_raw_parts_mut(ptr, new_capacity))
  };
  </code></pre>
  
  <p>However, the documentation for <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw" rel="noreferrer"><code>Box::from_raw</code></a> states (emphasis added):</p>
  
  <blockquote>
    <p>Since the way Box allocates and releases memory is unspecified, <strong><em>the only valid pointer to pass to this function</em></strong> is the one taken from another Box via the <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw" rel="noreferrer"><code>Box::into_raw</code></a> function.</p>
  </blockquote>
  
  <p>For the avoidance of doubt, the (experimental) <a href="https://doc.rust-lang.org/std/heap/struct.Heap.html" rel="noreferrer"><code>Heap</code></a> API used above to perform memory allocation (since removed in Rust 1.27.0) directly called <code>__rust_alloc</code> in its <a href="https://doc.rust-lang.org/1.26.2/src/alloc/heap.rs.html#82-92" rel="noreferrer"><code>alloc</code></a> method—and therefore <code>ptr</code> was <em>not</em> obtained from <code>Box::into_raw</code>.</p>
  
  <p>Is it valid, albeit unsupported, to pass to <code>Box::from_raw</code> raw pointers to freshly allocated memory in order to have Rust take ownership of that memory and enforce its usual safety and containment checks?  In particular, will Rust deallocate that memory when the arising Box is destroyed?</p>
  
  <p>If not, how <em>can</em> one force Rust to take such ownership of memory allocated other than by its safe methods?</p>