Skip to content

heapless Vec does not work good with stacked borrows, while std Vec does #514

@Rosdf

Description

@Rosdf

Pushing to heapless:Vec invalidates all previously created pointers into Vector

small example

fn vector() {
    let mut a = Vec::with_capacity(10);
    a.push(1);

    let b = std::ptr::from_ref(a.get(0).unwrap());
    a.push(1);

    println!("{:?}", unsafe { *b });
}

fn heapless_vector() {
    let mut a = heapless::Vec::<i32, 10>::new();
    a.push(1).unwrap();

    let b = std::ptr::from_ref(a.get(0).unwrap());
    a.push(1).unwrap();

    println!("{:?}", unsafe { *b });
}

miri shows error

running 2 tests
test test::heapless_vector ... error: Undefined Behavior: attempting a read access using <261088> at alloc102617[0x8], but that tag does not exist in the borrow stack for this location
  --> src/main.rs:25:35
   |
25 |         println!("{:?}", unsafe { *b });
   |                                   ^^
   |                                   |
   |                                   attempting a read access using <261088> at alloc102617[0x8], but that tag does not exist in the borrow stack for this location
   |                                   this error occurs as part of an access at alloc102617[0x8..0xc]
   |
   = 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: <261088> was created by a SharedReadOnly retag at offsets [0x8..0xc]
  --> src/main.rs:22:17
   |
22 |         let b = std::ptr::from_ref(a.get(0).unwrap());
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: <261088> was later invalidated at offsets [0x0..0x30] by a Unique function-entry retag inside this call
  --> src/main.rs:23:9
   |
23 |         a.push(1).unwrap();
   |         ^^^^^^^^^
   = note: BACKTRACE (of the first span) on thread `test::heapless_`:
   = note: inside `test::heapless_vector` at src/main.rs:25:35: 25:37
note: inside closure
  --> src/main.rs:18:25
   |
17 |     #[test]
   |     ------- in this procedural macro expansion
18 |     fn heapless_vector() {
   |                         ^
   = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)

right now i don't see any way to go around it, except for method like this

unsafe fn push_by_ptr(this: *mut Self, item: T)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions