Skip to content

Questions around UB and references to dropped data #4668

@hkBst

Description

@hkBst

For a discussion here, we tried the following things:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=1c4f3446888f2b92d486a5f478722640:

fn main() {
    let mut s = "goijiotrgjh".to_string();
    
    // simulate if it were droppped immediately
    unsafe { std::ptr::drop_in_place(&mut s) };
    
    let ptr = s.as_ptr(); // miri says: UB: dangling pointer, but this is perhaps a dangling reference?
    //let a = s.len();
    //dbg!(a);
}

I think that is at least not fully correct, since a dangling pointer by itself is not UB, only dereferencing it, right?

But:

fn main() {
    let mut s: &str = &"goijiotrgjh".to_string();
    
    // simulate if it were droppped immediately
    unsafe { std::ptr::drop_in_place(&mut s) }; // possibly already UB here, since this creates a dangling reference, or?
    
    let ptr = s as *const str;
    let a = s.len(); // miri does not complain..., but this is definitely(?) UB: a dereferenced dangling pointer
    dbg!(a);
}

or perhaps:

fn main() {
    let s: &mut str = &mut "goijiotrgjh".to_string();
    
    // simulate if it were droppped immediately
    unsafe { std::ptr::drop_in_place(&mut *s) }; // already UB here, since this creates a dangling reference?
    
    let ptr = s as *const str;
    let a = s.len(); // miri does not complain..., but this is definitely(?) UB: a dereferenced dangling pointer
    dbg!(a);
}

If anyone can shed some light on this...

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