Skip to content

Miri does not catch UB when swap_nonoverlapping is used on the same ptr #4188

Closed
rust-lang/rust
#136890
@Phoqinu

Description

@Phoqinu

Hello, I was writing a lot of unsafe in my lib and it passed tests with cargo miri test but running cargo test crashed with:

unsafe precondition(s) violated: ptr::swap_nonoverlapping requires that both pointer arguments are aligned and non-null and the specified memory ranges do not overlap

So I made this example:

use std::{
    alloc::{Layout, alloc, dealloc},
    ptr,
};

fn main() {
    let layout = Layout::new::<usize>();
    let ptr_layout = Layout::array::<usize>(2).unwrap();
    let ptr = unsafe { alloc(ptr_layout) };

    unsafe { ptr.cast::<usize>().add(0).write(0_usize) };
    unsafe { ptr.cast::<usize>().add(1).write(0_usize) };

    unsafe {
        ptr::swap_nonoverlapping(ptr, ptr, layout.size());
    }

    unsafe {
        dealloc(ptr, ptr_layout);
    };
}

One of the Safety requirements of ptr::swap_nonoverlapping is The region of memory beginning at x with a size of count * size_of::<T>() bytes must not overlap with the region of memory beginning at y with the same size. but miri does not catch this.

While it panics in debug mode without running miri I think miri should catch this... or not ?

Metadata

Metadata

Assignees

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