Skip to content

Segfault in safe code: Index trait sugar v[i] ignores the borrow checker #15525

Closed
@japaric

Description

@japaric

STR:

struct MyVec<T> {
    data: Vec<T>,
}

impl<T> Index<uint, T> for MyVec<T> {
    fn index<'a>(&'a self, &i: &uint) -> &'a T {
        assert!(i < self.data.len());
        &self.data.as_slice()[i]
    }
}

fn main() {
    let v = MyVec { data: vec!(box 1i, box 2, box 3) };

    let ok: &Box<int> = v.index(&0);

    // Partial move while `v` is borrowed
    let bad: Box<int> = v[0];

    // Boom!
    println!("{}", good);
}

Output:

$ rustc foo.rs && ./foo
[1]    20073 segmentation fault (core dumped)  ./foo

GDB:

$ gdb ./foo
(..)
Program received signal SIGSEGV, Segmentation fault.
0x0000000000489c79 in fmt::num::int.fmt..Show::fmt::he5f803ef1f438abdOsJ ()
(..)

Version:

$ rustc --version
rustc 0.11.0 (e2e237afc1f9887699414c33332faa1efaba41ce 2014-07-08 09:56:41 +0000)

cc @pcwalton

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions