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

Fix leak of memory if dropping function panic #360

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
29 changes: 29 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8379,4 +8379,33 @@ mod test_map {

map2.clone_from(&map1);
}

// Test that map do not leak memory if dropping function panic
#[test]
#[should_panic = "panic in drop"]
fn test_panic_in_drop() {
#[derive(Clone)]
struct CheckedDrop {
panic_in_drop: bool,
}
impl Drop for CheckedDrop {
fn drop(&mut self) {
if self.panic_in_drop {
panic!("panic in drop");
}
}
}
const DISARMED: CheckedDrop = CheckedDrop {
panic_in_drop: false,
};
const ARMED: CheckedDrop = CheckedDrop {
panic_in_drop: true,
};

let mut map1 = HashMap::new();
map1.insert(1, DISARMED);
map1.insert(2, DISARMED);
map1.insert(3, ARMED);
map1.insert(4, DISARMED);
}
}
26 changes: 22 additions & 4 deletions src/raw/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1803,8 +1803,17 @@ unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable<T, A> {
fn drop(&mut self) {
if !self.table.is_empty_singleton() {
unsafe {
self.drop_elements();
self.free_buckets();
// Guard that provide deallocation of memory even if any panics occurs during dropping
let mut self_ = guard(self, |self_| {
self_.free_buckets();
});

// This may panic but in any case the scope guard will deallocate memory of
// the table, leaking any elements that were not dropped yet if panic occurs.
//
// This leak is unavoidable: we can't try dropping more elements
// since this could lead to another panic and abort the process.
self_.drop_elements();
}
}
}
Expand All @@ -1815,8 +1824,17 @@ impl<T, A: Allocator + Clone> Drop for RawTable<T, A> {
fn drop(&mut self) {
if !self.table.is_empty_singleton() {
unsafe {
self.drop_elements();
self.free_buckets();
// Guard that provide deallocation of memory even if any panics occurs during dropping
let mut self_ = guard(self, |self_| {
self_.free_buckets();
});

// This may panic but in any case the scope guard will deallocate memory of
// the table, leaking any elements that were not dropped yet if panic occurs.
//
// This leak is unavoidable: we can't try dropping more elements
// since this could lead to another panic and abort the process.
self_.drop_elements();
}
}
}
Expand Down