Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using an iterator in a for loop doesn't borrow the object #16820

Closed
elinorbgr opened this issue Aug 28, 2014 · 1 comment · Fixed by #17101
Closed

Using an iterator in a for loop doesn't borrow the object #16820

elinorbgr opened this issue Aug 28, 2014 · 1 comment · Fixed by #17101
Milestone

Comments

@elinorbgr
Copy link
Contributor

This simple code compiles on current master (0d3bd77) :

fn main() {
    let mut vector = vec!(1u, 2u);
    for &x in vector.iter() {
        let cap = vector.capacity();
        println!("Capacity was: {}", cap);
        vector.grow(cap, &0u); // be sure to cause reallocation
        *vector.get_mut(1u) = 5u;
        println!("Value: {}", x);
    }
}

and outputs:

Capacity was: 4
Value: 1
Capacity was: 8
Value: 2

while on 0.11 the borrow checker would complain that vector is already immutably borrowed by vector.iter().
It allows me to write 5u in vector[1] and then read it as 2u, because reallocation of the vector caused the iterator's slice to refer to freed memory.

(was found in a StackOverflow question : http://stackoverflow.com/q/25528271/2536143 )

@alexcrichton
Copy link
Member

cc @pcwalton and nominating, seems bad!

@huonw huonw added the I-wrong label Aug 31, 2014
@brson brson added this to the 1.0 milestone Sep 4, 2014
pcwalton added a commit to pcwalton/rust that referenced this issue Sep 8, 2014
itself.

This breaks code like:

    for &x in my_vector.iter() {
        my_vector[2] = "wibble";
        ...
    }

Change this code to not invalidate iterators. For example:

    for i in range(0, my_vector.len()) {
        my_vector[2] = "wibble";
        ...
    }

The `for-loop-does-not-borrow-iterators` test for rust-lang#8372 was incorrect
and has been removed.

Closes rust-lang#16820.

[breaking-change]
bors added a commit to rust-lang-ci/rust that referenced this issue Mar 17, 2024
…r=lnicola

fix: Don't auto-close block comments in strings

Fixes rust-lang#16815
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants