Skip to content

Unsound behavior when returning &-pointers #9069

Closed
@alexcrichton

Description

@alexcrichton

This code:

struct A<'self> {
    cur: &'self mut int
}

impl<'self> Iterator<&'self int> for A<'self> {
    fn next(&mut self) -> Option<&'self int> {
        *self.cur += 1;
        return Some(&*self.cur);
    }
}

fn main() {
    let mut a = 3;
    let mut a = A { cur: &mut a };
    let b = a.next();
    println!("{:?}", b);
    let c = a.next();
    println!("{:?}", b);
    println!("{:?}", c);
}

Runs with:

$ rustc foo.rs
warning: no debug symbols in executable (-arch x86_64)
$ ./foo
Some(&4)
Some(&5)
Some(&5)

I thought something like this should be a compiler error? It seems to me that the lifetime of b would conflict with attempting to re-borrow a as mut.

cc @nikomatsakis

@blake2-ppc discovered this in a bug in a test he wrote for #9062

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