Fix memory leak

This commit is contained in:
Quentin Legot
2023-03-22 14:30:21 +01:00
parent b9c329219a
commit b104bcc6da
2 changed files with 6 additions and 5 deletions

View File

@ -108,13 +108,14 @@ impl<T: PartialEq> List<T> {
/// Return true if the item has been found, otherwise return false
///
/// Worst-case complexity is O(n)
pub fn remove(&mut self, item: &T)-> bool {
pub fn remove(&mut self, item: T)-> bool {
unsafe {
let mut current: *mut Node<T> = self.head;
let mut previous: *mut Node<T> = ptr::null_mut();
while !current.is_null() {
if &(*current).elem == item {
if (*current).elem == item {
(*previous).next = (*current).next;
drop(Box::from_raw(current).elem);
return true;
} else {
previous = current;
@ -312,11 +313,11 @@ mod test {
list.push(3);
assert_eq!(list.contains(&2), true);
list.remove(&2);
list.remove(2);
assert_eq!(list.contains(&2), false);
assert_eq!(list.pop(), Option::Some(1));
assert_eq!(list.pop(), Option::Some(3));
assert_eq!(list.pop(), Option::None);
assert_eq!(list.peek(), Option::None);
}
#[test]