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

expand leak amplification with example #455

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/leaking.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,47 @@ mem::forget us in the middle of the iteration, all that does is *leak even more*
Since we've accepted that mem::forget is safe, this is definitely safe. We call
leaks causing more leaks a *leak amplification*.

Expanding the above example shows that elements remaining in the vector after
dropping the `drainer` are leaked:

<!-- ignore: simplified code -->
```rust
use std::mem;

struct Frob {
v: i32,
}

impl Drop for Frob {
fn drop(&mut self) {
println!("Frob {{ v: {} }} dropped", self.v)
}
}

fn main() {
let mut vec = (1..5).map(|v| Frob { v }).collect::<Vec<_>>();

{
let mut drainer = vec.drain(..);

drainer.next();
drainer.next();

mem::forget(drainer);
}

println!("Goodbye");
}
```

Output:

```text
Frob { v: 1 } dropped
Frob { v: 2 } dropped
Goodbye
```

## Rc

Rc is an interesting case because at first glance it doesn't appear to be a
Expand Down
Loading