How to test a memory allocator with miri?

I'm writing a memory allocator in Rust, and to test it I want to simulate a heap with Vec<u8> and test my allocator on it. I'd like to run the tests with miri, but it does not let me write anything that is not u8 onto my "heap".

Here's a link to MRE on the playground, and this is the error message I get from miri:

error: Undefined Behavior: attempting a write access using <10731> at alloc1530[0x1], but that tag does not exist in the borrow stack for this location
  --> src/main.rs:11:13
   |
11 |     unsafe {ptr.cast::<usize>().write(42_usize)};
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |             |
   |             attempting a write access using <10731> at alloc1530[0x1], but that tag does not exist in the borrow stack for this location
   |             this error occurs as part of an access at alloc1530[0x0..0x8]
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <10731> was created by a SharedReadWrite retag at offsets [0x0..0x1]
  --> src/main.rs:9:16
   |
9  |     let ptr =  &mut backing[0] as *mut u8;
   |                ^^^^^^^^^^^^^^^
   = note: BACKTRACE (of the first span):
   = note: inside `main` at src/main.rs:11:13: 11:48

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to 1 previous error; 1 warning emitted
  1. What does this error message mean?
  2. Is there a better way I can test my allocator with miri?

&mut backing[0] gives you a reference to the first element and only the first element. Try Vec::as_mut_ptr if you need a pointer to the whole vec) buffer.

Thanks! That solved it.

I have a further (perhaps silly) question: how are the two pointers actually different? Conceptually it seems that both would point to the begging of the region where the vector lives

I can recommend Ralf Jung's blog posts on pointers for some background

3 Likes