Skip to content

Segfault in safe code caused by a use after drop when using index sugar #30438

Closed
@phsym

Description

@phsym

I've been playing a bit around std::ops::Index and the associated sugar.
I found a case where it may cause a segfault. I tried to reproduce the issue in a simplified code and got the following one (also available on playpen)

use std::ops::Index;

struct Test<'a> {
    s: &'a String
}

impl <'a> Index<usize> for Test<'a> {
    type Output = Test<'a>;
    fn index(&self, _: usize) -> &Self::Output {
        return &Test { s: &self.s};
    }
}

fn main() {
    let s = "Hello World".to_string();
    let test = Test{s: &s};
    let r = &test[0];
    println!("{}", test.s); // OK since test is valid
    println!("{}", r.s); // Segfault since value pointed by r has already been dropped
}

I guess this code should not compile since on the last line, r points to a dropped value.

Metadata

Metadata

Assignees

Labels

I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-highHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions